C#Linq从ToDictionary获得不正确的结果

Rus*_*ail 0 c#

我有一些代码,寻找匹配,这里回答的问题给出了这个问题背后的一些历史.我正在查看数据集,排序和查找匹配项.

我的例子:

// 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());
Run Code Online (Sandbox Code Playgroud)

我明白了:

0: 1
10: 2
Run Code Online (Sandbox Code Playgroud)

我应该得到:

0: 3
10: 2
Run Code Online (Sandbox Code Playgroud)

我做错了什么?

Sel*_*enç 5

id是一个string:

.ToDictionary(id => id.ToString(), id => id.Count());
Run Code Online (Sandbox Code Playgroud)

因此它并不像您认为的那样代表集合.调用计数返回字符数而不是项目发生的次数.

您应该将LINQ查询更改为使用实际组而不是键:

IDs.GroupBy(id => id)
   .Where(id => id.Count() > 1)
   .ToDictionary(g => g.Key, g => g.Count());
Run Code Online (Sandbox Code Playgroud)