check whether a List contains an element in another List using LINQ

前端 未结 2 637
抹茶落季
抹茶落季 2020-12-16 16:20

How do I check whether a List contains an element that exists in another List using LINQ in C#? I don\'t want to use a for/while loop.

So, if List1 has A, B, C and L

相关标签:
2条回答
  • 2020-12-16 17:01

    Use Enumerable.Any Method:

    List<string> l1 = new List<string> { "1", "2" };
    List<string> l2 = new List<string> { "1", "3" };
    var result = l2.Any(s => l1.Contains(s));
    

    I'd say the Intersect method (see answer by dasblinkenlight) + Any must work better than Contains + Any. It is definetely better to use Any than Count.

    0 讨论(0)
  • 2020-12-16 17:15

    Try this:

    List<string> a = ...
    List<string> b = ...
    var inComon = a.Intersect(b).Any();
    
    0 讨论(0)
提交回复
热议问题