Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check whether a List<string> contains an element in another List<string> using LINQ

Tags:

c#

linq

How do I check whether a List contains an element that exists in another List using LINQ in C#? I don't want to use a for/while loop.

So, if List1 has A, B, C and List2 has B, 1, 2, then I would return true.

like image 409
Mark13426 Avatar asked Dec 05 '12 02:12

Mark13426


People also ask

How do you use LINQ to check if a list of strings contains any string in a list?

Any(tag => list. Contains(tag)); Or: var list = new List<string> { ... }; var query = query.

How do you check if an element of a list is in another list C#?

You could use a nested Any() for this check which is available on any Enumerable : bool hasMatch = myStrings. Any(x => parameters. Any(y => y.

How do you check if a list contains a particular string?

if (myList. Contains(myString)) string element = myList. ElementAt(myList. IndexOf(myString));

What is any () in Linq?

The Any operator is used to check whether any element in the sequence or collection satisfy the given condition. If one or more element satisfies the given condition, then it will return true. If any element does not satisfy the given condition, then it will return false.


1 Answers

Try this:

List<string> a = ...
List<string> b = ...
var inComon = a.Intersect(b).Any();
like image 77
Sergey Kalinichenko Avatar answered Oct 16 '22 20:10

Sergey Kalinichenko