将两个foreach语句合二为一

时间:2019-03-06 12:52:48

标签: c# linq

我有以下foreach语句,我希望将它们转换为linq查询。

var equalityGroup= new Dictionary<string, List<string>();
var firstGroup = new Dictionary<string, List<string>();
var request = new List<Request>();

foreach(var element in request) 
{
    var key = element.Number;
    if (!equalityGroup.ContainsKey(key))
    {
        equalityGroup.Add(key, new List<string>());
    }

    foreach(var item in firstGroup)
    {
        var query = item.Value.FindAll(y => y ==element.Id);
        if (query.Any())
        {
            equalityGroup[key].AddRange(query);
        }
    }
}

有人可以给我一个有关Linq的很好的例子吗?

1 个答案:

答案 0 :(得分:4)

我认为通过执行联接(内部使用哈希表)而不是嵌套循环,您应该能够大大提高大型集合的性能。

var firstGroup = new Dictionary<string, List<string>>();
var request = new List<Request>();

var q = from element in request
        join y in firstGroup.SelectMany(x => x.Value) on element.Id equals y
        group y by element.Id into g
        select new { g.Key, g };

var equalityGroup = q.ToDictionary(x => x.Key, x => x.g.ToList());