Find the intersection of two lists in linq?

后端 未结 6 470
迷失自我
迷失自我 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:40

    You can use Intersect:

    var a = new List<int>();
    var b = new List<int>();
    
    var c = a.Intersect(b);
    
    0 讨论(0)
  • 2020-12-29 01:40

    Produce a list c containing all elements that are present in both lists a and b:

    List<int> c = a.Intersect(b).ToList();
    
    0 讨论(0)
  • 2020-12-29 01:50

    You could use the Intersect method:

    var c = a.Intersect(b);
    

    This return all values both in a and b. However, position of the item in the list isn't taken into account.

    0 讨论(0)
  • 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<int>(a);
    var cList = b.Where(aSet.Contains)
                 .ToList(); 
    
    0 讨论(0)
  • 2020-12-29 02:04

    As Chris mentions in his comment on the original question, the sample code provided will return duplicates in list c (see his comment for details). Intersect will only return distinct values. To duplicate the behavior of the original sample code, try this:

    var c = (from value in a
             where b.Contains(a)
             select a);
    
    0 讨论(0)
  • 2020-12-29 02:06

    This is my version of intersection:

    var a = new List<int>();
    var b = new List<int>();
    
    // intersection
    var c = a.Where(x => b.Any(y => x == y)).ToList();
    
    0 讨论(0)
提交回复
热议问题