C#Linq从ToDictionary获得不正确的结果
我有一些代码,寻找匹配项,一个回答的问题给出了这个问题背后的一些历史。我正在查看数据集,排序并查找匹配项 我的例子是:C#Linq从ToDictionary获得不正确的结果,c#,C#,我有一些代码,寻找匹配项,一个回答的问题给出了这个问题背后的一些历史。我正在查看数据集,排序并查找匹配项 我的例子是: // Test Data: ConcurrentBag<string> One = new ConcurrentBag<string>() { "0", "1", "3", "5", "7", "9" }; ConcurrentBag<string> Two = new ConcurrentBag<string>() { "0",
// 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());
我应该得到:
0: 3
10: 2
我做错了什么?id这是一个
字符串
:
.ToDictionary(id => id.ToString(), id => id.Count());
所以它并不像你想象的那样代表这个集合。调用count返回项目发生的字符数,而不是次数
您应该将LINQ查询更改为使用实际组而不是键:
IDs.GroupBy(id => id)
.Where(id => id.Count() > 1)
.ToDictionary(g => g.Key, g => g.Count());
id
这里是一个字符串
:
.ToDictionary(id => id.ToString(), id => id.Count());
所以它并不像你想象的那样代表这个集合。调用count返回项目发生的字符数,而不是次数
您应该将LINQ查询更改为使用实际组而不是键:
IDs.GroupBy(id => id)
.Where(id => id.Count() > 1)
.ToDictionary(g => g.Key, g => g.Count());
啊,该死,我早该想到的,太谢谢你了!啊,该死,我早该想到的,太谢谢你了!