Find if listA contains any elements not in listB

后端 未结 7 701
春和景丽
春和景丽 2020-11-30 03:25

I have two lists:

List listA     
List listB

How to check using LINQ if in the listA exists an element w

相关标签:
7条回答
  • 2020-11-30 04:08

    List has Contains method that return bool. We can use that method in query.

    List<int> listA = new List<int>();
    List<int> listB = new List<int>();
    listA.AddRange(new int[] { 1,2,3,4,5 });
    listB.AddRange(new int[] { 3,5,6,7,8 });
    
    var v = from x in listA
            where !listB.Contains(x)
            select x;
    
    foreach (int i in v)
        Console.WriteLine(i);
    
    0 讨论(0)
  • 2020-11-30 04:14

    This piece of code compares two lists both containing a field for a CultureCode like 'en-GB'. This will leave non existing translations in the list. (we needed a dropdown list for not-translated languages for articles)

    var compared = supportedLanguages.Where(sl => !existingTranslations.Any(fmt => fmt.CultureCode == sl.Culture)).ToList();

    0 讨论(0)
  • 2020-11-30 04:17
    if (listA.Except(listB).Any())
    
    0 讨论(0)
  • 2020-11-30 04:25

    You can do it in a single line

    var res = listA.Where(n => !listB.Contains(n));
    

    This is not the fastest way to do it: in case listB is relatively long, this should be faster:

    var setB = new HashSet(listB);
    var res = listA.Where(n => !setB.Contains(n));
    
    0 讨论(0)
  • 2020-11-30 04:25

    Get the difference of two lists using Any(). The Linq Any() function returns a boolean if a condition is met but you can use it to return the difference of two lists:

    var difference = ListA.Where(a => !ListB.Any(b => b.ListItem == a.ListItem)).ToList();
    
    0 讨论(0)
  • 2020-11-30 04:26
    listA.Any(_ => listB.Contains(_))
    

    :)

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