并发集合的最快迭代? [英] Fastest iterating of concurrent collections?
问题描述
我有一个难题,我需要遍历以下数据结构:
I have a conundrum, I need to iterate over the following data structure:
public ConcurrentDictionary<int, ConcurrentBag<string>> BaseCollection { get; set; }
private void Form1_Load(object sender, EventArgs e)
{
// 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;
}
private void Find_Click(object sender, EventArgs e)
{
// 3 Dictionary Items:
var Items = BaseCollection.Select((k, v) => new { k, v });
// I am a little stuck...
// We should only find "0" and "10"
// Knowing we need to look for "0" I can use the following to find it's frequency using:
var Item = Items.SelectMany(i => i.k.Value).Select(a => a).Where(a => a == "0");
}
说五个字典项,最多包含数千个并发字符串
Say Five Dictionary Items with up to thousands of ConcurrentBags of strings
我需要找到Dictionary集合之间的字符串匹配.
I need to find String Matches between Dictionary collections.
我想到了嵌套循环,想到了Linq,但是我对Linq并不熟练:
I thought about nested for loops, I thought about Linq, but I am not very skilled at Linq:
BaseCollection.Select((k, v) => new { k, v }).Where((k, v) => k.k.Value == k.k.Value);
如果有人可以指出正确的方向,那么我可以最好的方式考虑一下.谢谢.
If someone can point me in the right direction, so I can think about this in the best way. Thanks.
推荐答案
如果要在所有 ConcurrentBag
s中包含唯一条目列表:
If you want a list of unique entries across all of the ConcurrentBag
s:
var IDs = BaseCollection.SelectMany(u => u.Value);
var duplicateIDs = IDs.Distinct().ToList();
如果您希望这些出现不止一次:
If you want those that appear more than once:
var IDs = BaseCollection.SelectMany(u => u.Value);
var multipleTimes = IDs
.GroupBy(z => z)
.Where(z => z.Count() > 1)
.Select(z => z.Key)
.ToList();
SelectMany
进行投影以获取所有 ConcurrentBag
中的所有条目. Distinct
删除重复项. GroupBy
和 Where
允许按匹配数进行过滤. ToList
将结果输出为 List< int>
.
SelectMany
does a projection to get all entries across all of the ConcurrentBag
s. Distinct
removes duplicates. GroupBy
and Where
allows filtering by how many matches there are. ToList
outputs the results as a List<int>
.
.Where(z => z.Count() > 1)
也可以替换为:
.Where(z => z.AtLeast(2))
如果您使用 MoreLinq .您需要分析代码(通过多次调用)以查看其是否提高了性能.
这篇关于并发集合的最快迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!