Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#Linq从ToDictionary获得不正确的结果_C# - Fatal编程技术网

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());

啊,该死,我早该想到的,太谢谢你了!啊,该死,我早该想到的,太谢谢你了!