How should I compare values in two lists?

前端 未结 4 759
臣服心动
臣服心动 2021-02-05 13:39

I have two lists

List 01 => { A, B, C, D, E }
List 02 => { F, F, F, F, E }

I need to check if one element of List 02 exists

4条回答
  •  爱一瞬间的悲伤
    2021-02-05 14:12

    try

    list1.Any(e => list2.Contains(e));
    

    e.g.

    var list1 = new List { "A", "B", "C", "D" };
    var list2 = new List { "F", "F", "F" };
    
    list1.Any(e => list2.Contains(e)); // returns false
    
    var list3 = new List { "F", "F", "D" };
    
    list1.Any(e => list3.Contains(e)); // returns true
    

    UPDATE: as leppie points out, using Intersect will be more performant, esp if the lists are large.

提交回复
热议问题