A Dictionary by default uses exact lookups. It computes a hash code based on a key and if another value matches it exactly, the two keys match. But this can be changed.
using System;
using System.Collections.Generic;
class CustomComparer : IEqualityComparer<string>
{
public bool Equals(string x, string y)
{
int xPos = 0;
int yPos = 0;
while (true)
{
// ... Fail if past end.
if (xPos >= x.Length)
{
return false;
}
if (yPos >= y.Length)
{
return false;
}
// ... Skip past hyphens.
if (x[xPos] == '-')
{
xPos++;
continue;
}
if (y[yPos] == '-')
{
yPos++;
continue;
}
// ... Fail if different.
if (x[xPos] != y[yPos])
{
return false;
}
// ... If we have traversed both strings with no error, we match.
if (xPos == x.Length - 1 && yPos == y.Length - 1)
{
return true;
}
// ... Increment both places.
xPos++;
yPos++;
}
}
public int GetHashCode(string obj)
{
int code = 0;
// ... Add together all chars.
for (int i = 0; i < obj.Length; i++)
{
if (obj[i] != '-')
{
code += obj[i];
}
}
return code;
}
}
class Program
{
static void Main()
{
// ... Add data to dictionary.
var dictionary = new Dictionary<string, int>(new CustomComparer());
dictionary[
"cat-1"] = 1;
dictionary[
"cat-2"] = 2;
dictionary[
"dog-bark"] = 10;
dictionary[
"dog-woof"] = 20;
// ... Lookup values, ignoring hyphens.
Console.WriteLine(dictionary[
"cat1"]);
Console.WriteLine(dictionary[
"cat-1"]);
Console.WriteLine(dictionary[
"dog--bark"]);
}
}
1
1
10