C# Linq getting incorrect results from ToDictionary

2200 views c#
-4

I have some code, looking for matches, an answered question here gives some history behind this question. I am looking at a dataset, sorting and finding matches.

My example:

// Test Data:
ConcurrentBag<string> One = new ConcurrentBag<string>() { "0", "1", "3", "5", "7", "9" };
ConcurrentBag<string> Two = new ConcurrentBag<string>() { "0", "2", "4", "6", "8", "10" };
ConcurrentBag<string> Three = new ConcurrentBag<string>() { "0", "10", "20", "30", "40" };

// Init new Index:
BaseCollection = new ConcurrentDictionary<int, ConcurrentBag<string>>();
BaseCollection[0] = One;
BaseCollection[1] = Two;
BaseCollection[2] = Three;

// Get all Id's in this Collection:
var IDs = BaseCollection.SelectMany(u => u.Value);

// Sort and extract Matches:
var Matches = IDs.GroupBy(id => id)
                 .Where(id => id.Count() > 1)
                 .Select(id => id.Key).Distinct()
                 .ToDictionary(id => id.ToString(), id => id.Count());

I get:

0: 1
10: 2

I should get:

0: 3
10: 2

What have I done wrong?

answered question

1 Answer

10

The id here is a string:

.ToDictionary(id => id.ToString(), id => id.Count());

So it doesn't represent the collection as you think it does. Calling count returns the number of characters instead of the number of times an item is occurred.

You should change your LINQ query to use actual group rather than the key:

IDs.GroupBy(id => id)
   .Where(id => id.Count() > 1)
   .ToDictionary(g => g.Key, g => g.Count());

posted this

Have an answer?

JD

Please login first before posting an answer.

Ads

Categories