作者:关圣钊 | 来源:互联网 | 2022-11-30 16:55
我有一些代码,寻找匹配,这里回答的问题给出了这个问题背后的一些历史.我正在查看数据集,排序和查找匹配项.
我的例子:
// Test Data:
ConcurrentBag One= new ConcurrentBag() { "0", "1", "3", "5", "7", "9" };
ConcurrentBag Two = new ConcurrentBag() { "0", "2", "4", "6", "8", "10" };
ConcurrentBag Three = new ConcurrentBag() { "0", "10", "20", "30", "40" };
// Init new Index:
BaseCollection = new ConcurrentDictionary>();
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: 1
10: 2
我应该得到:
0: 3
10: 2
我做错了什么?
1> Selman Genç..:
这id
是一个string
:
.ToDictionary(id => id.ToString(), id => id.Count());
因此它并不像您认为的那样代表集合.调用计数返回字符数而不是项目发生的次数.
您应该将LINQ查询更改为使用实际组而不是键:
IDs.GroupBy(id => id)
.Where(id => id.Count() > 1)
.ToDictionary(g => g.Key, g => g.Count());