Find the intersection of two lists in linq?

后端 未结 6 497
迷失自我
迷失自我 2020-12-29 01:04

I have list of int A,B. i like to do the following step in linq

list c = new List();

for (int i = 0; i < a.count; i++)
{
    for (i         


        
6条回答
  •  一个人的身影
    2020-12-29 01:51

    The LINQ equivalent of your code is:

    var c = from i in Enumerable.Range(0, a.Count)
            from j in Enumerable.Range(0, b.Count)
            where a[i] == b[j]
            select a[i];
    
    var cList = c.ToList();
    

    But it's much nicer to do:

    var c = from aItem in a 
            join bItem in b on aItem equals bItem
            select aItem;
    
    var cList = c.ToList();
    

    But this doesn't filter duplicates. To filter duplicates completely, you can do:

    var cList = a.Intersect(b).ToList();
    

    If you want duplicates to show up as many times as they do in b, for example:

    var aSet = new HashSet(a);
    var cList = b.Where(aSet.Contains)
                 .ToList(); 
    

提交回复
热议问题