并发集合的最快迭代?

时间:2018-10-31 23:14:28

标签: c# collections

我有一个难题,我需要遍历以下数据结构:

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");
}

说五个字典项,最多包含数千个并发字符串

我需要找到Dictionary集合之间的字符串匹配。

我想到了嵌套循环,想到了Linq,但是我对Linq并不熟练:

BaseCollection.Select((k, v) => new { k, v }).Where((k, v) => k.k.Value == k.k.Value);

如果有人可以指出正确的方向,那么我可以最好的方式考虑一下。谢谢。

2 个答案:

答案 0 :(得分:3)

如果您想要所有ConcurrentBag上的唯一条目列表:

var IDs = BaseCollection.SelectMany(u => u.Value);
var duplicateIDs = IDs.Distinct().ToList();

如果您希望这些内容不止一次出现:

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删除重复项。 GroupByWhere允许按匹配数进行过滤。 ToList将结果输出为List<int>

.Where(z => z.Count() > 1)

也可以替换为:

.Where(z => z.AtLeast(2))

如果您使用MoreLinq您需要分析代码(通过多次调用)以查看其是否提高了性能。

答案 1 :(得分:0)

好吧,经过很多困惑之后,人们已经得出了各种各样的答案。

没有错误检查或重复检查:

private void Find_Click(object sender, EventArgs e)
{

    var IDs = BaseCollection.SelectMany(u => u.Value);

    foreach (string id in IDs)
    {
        var Items = BaseCollection.Select((k, v) => new { k, v });
        var Item = Items.SelectMany(i => i.k.Value).Select(a => a).Where(a => a == id);

        int Count = Item.Count();

        if(Count > 1) // Duplicate Found, Figure out what to do...
    }
}

我相信这在速度和准确性上都可以大大改善。