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);
listA.Any(_ => listB.Contains(_))
:)
if (listA.Except(listB).Any())
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));
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();
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();
Source: Stackoverflow.com