Prakazz Prakazz - 3 years ago 256
C# Question

Handle Collision using Hashtable Class in c#

In the below scenario how can I handle or implement collision in C# using the Hashtable class? If the 'Key' value is same I am getting an "Argument Exception".

static void Main(string[] args)
{
Console.Write("Enter a string:");
string input = Console.ReadLine();

checkString(input);

Console.ReadLine();
}

static void checkString(string input)
{
Hashtable hashTbl = new Hashtable();

foreach(char c in input)
{
hashTbl.Add(c.GetHashCode(), c);
}

printHash(hashTbl);
}

static void printHash(Hashtable hash)
{
foreach(int key in hash.Keys)
{
Console.WriteLine("Key: {0} Value: {1}",key,hash[key]);
}
}


My Expectation:
What do I need to do in the 'Value' argument to get around the 'Collision' issue. I am trying to check if the string consists of unique characters.

Answer Source

I am trying to check if the string consists of unique characters.

Then you need keys only without values, that's what HashSet<T> is for.

var chars = new HashSet<char>();
foreach (char c in input)
{
    if (chars.Contains(c))
    {
        // c is not unique
    }
    else
    {
        chars.Add(c);
    }
}

But I'd prefer usin LINQ in this case:

var hasUniqueChars = input.Length == input.Distinct().Count();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download