Find items from a list which exist in another list

后端 未结 4 350
攒了一身酷
攒了一身酷 2020-12-08 19:13

I have a List

PropA  
{  
    int a;  
    int b;  
}

and another List

         


        
相关标签:
4条回答
  • 2020-12-08 19:28
    ListA.Where(a => ListX.Any(x => x.b == a.b))
    
    0 讨论(0)
  • 2020-12-08 19:32

    What you want to do is Join the two sequences. LINQ has a Join operator that does exactly that:

    List<PropX> first;
    List<PropA> second;
    
    var query = from firstItem in first
        join secondItem in second
        on firstItem.b equals secondItem.b
        select firstItem;
    

    Note that the Join operator in LINQ is also written to perform this operation quite a bit more efficiently than the naive implementations that would do a linear search through the second collection for each item.

    0 讨论(0)
  • 2020-12-08 19:36

    Well all above will not work if you have multiple parameters, So I think this is the best way to do it.

    For example: Find not matched items from pets and pets2 .

    var notMatchedpets = pets
        .Where(p2 => !pets2
        .Any(p1 => p1.Name == p2.Name && p1.age == p2.age))
        .ToList();
    
    0 讨论(0)
  • 2020-12-08 19:42
    var commonNumbers = first.Intersect(second); 
    

    This will give you the common values between two lists, a much faster and cleaner approach than join or other Lambda expressions.

    Just try it.

    Source : MSDN

    0 讨论(0)
提交回复
热议问题