Question

Reference to many links for Lists comparision Compare two lists C# linq still I'm really not getting matching between the lists clearly.

Let's say I have two lists of strings:

 List1: "apple, orange, mango, bananna, butter fruit"

 List2: "butter fruit, grapes, apple, bananna, orange, mango, jack fruit, pineapple"

Here i need to check whether the List1 items are there in List2 set or not. If it is there return true otherwise false.

I tried with Except but not getting the expected result true or false between the sets.

if(List1.Except(List2).Count == 0)
{
  ....
}
Était-ce utile?

La solution

With Except

if(list1.Except(list2).Any())
{
   //....
}

With All(Bobson's comment: Be warned that .All() will succeed if list1 is empty, but the other two will not):

list1.All(str => list2.Contains(str));

With Any:

list1.Any(str => !list2.Contains(str));

Autres conseils

You can use All method:

return list1.All(list2.Contains);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top