Home > Software engineering >  C# LINQ Any() Comparig two Lists
C# LINQ Any() Comparig two Lists

Time:11-02

I have two lists

List<string> setA = new List<string>() {"cat", "dog", "elephant"};

List<string> setB = new List<string>() {"cat"};

I have bool bool compare = setA.Any(x => x.Equals(setB.Select(y => y))); which suppose to check for me if any string from setA eqauls string 'cat' from setB. it suppose to be 'true' but it isnt :/ (showing me as 'false')

What Im doing wrong?

CodePudding user response:

Your approach is wrong:

bool compare = setA.Any(x => x.Equals(setB.Select(y => y)));

This does following: checking if any strings in setA equal the IEnumerable<string> instance returned from setB.Select(y => y). So you are basically comparing a string with a LINQ query which is never true.

This is the most efficient way to check if any string in A is in B:

bool compare = setA.Intersect(setB).Any();

You can also use this, which is less efficient if the lists are large;

bool compare = setA.Any(setB.Contains);
  •  Tags:  
  • linq
  • Related