I have two lists:
List<int> listA
List<int> listB
How to check using LINQ if in the listA
exists an element wchich deosn't exists in the listB
? I can use the foreach
loop but I'm wondering if I can do this using LINQ
I have two lists:
List<int> listA
List<int> listB
How to check using LINQ if in the listA
exists an element wchich deosn't exists in the listB
? I can use the foreach
loop but I'm wondering if I can do this using LINQ
listA.Except(listB)
will give you all of the items in listA that are not in listB
listA.Any(_ => listB.Contains(_))
:)
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));
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);
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();