Calin Paul Alexandru
Calin Paul Alexandru

Reputation: 4752

SortedDictionary duplicate keys?

Okai, i have the following method:

public void Insert(SortedDictionary<byte[], uint> recs)
{
    SortedDictionary<byte[], uint> records = new SortedDictionary(recs, myComparer);
}

What I am hoping to achieve is to sort the records in "recs" with a new rule specified by "myComparer" which implements IComparer. It pretty much does so, but I get hit by an exception with the following message:

An entry with the same key already exists.

I am wondering how this is possible since "recs" is already a dictionary with about 130k keys.


    public int Compare(byte[] a, byte[] b)
    {
        return  Inhouse.ByteConverter.ToString(a).CompareTo(  
                    Inhouse.ByteConverter.ToString(b));
    }

(it's just a snipette..)

Upvotes: 0

Views: 4030

Answers (3)

William Mioch
William Mioch

Reputation: 917

You must be using the same Dictionary object in the calling method. So I imagine your code is something like this:

 SortedDictionary<byte[], uint> dic = new SortedDictionary<byte[], uint>();
 foreach (var thing in things)
 {
     dic.Clear();
     Populate(dic);
     Insert(dic);
 }

Where it should be like this:

SortedDictionary<byte[], uint> dic = new SortedDictionary<byte[], uint>();
foreach (var thing in things)
{
    dic = new SortedDictionary<byte[], uint>();
    Populate(dic);
    Insert(dic);
}

Can you post the code that is calling your Insert method?

Upvotes: 0

manji
manji

Reputation: 47978

Check the comparer code:

Every key in a SortedDictionary(Of TKey, TValue) must be unique according to the specified comparer; therefore, every key in the source dictionary must also be unique according to the specified comparer.

with your new comparer, 2 different keys with normal byte[] comparaison may become equal.

It's what msdn says...

Upvotes: 0

faester
faester

Reputation: 15076

If "recs" has a different comparer than the one you inject into records you may get duplicates; that is if "recs" compares by object reference and myComparer compares the actual bytes, you will have collisions.

Upvotes: 1

Related Questions