Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we check whether one array contains one or more elements of another array in #?

Tags:

c#

.net

I have a an array of strings:e.g:

string [] names ={"P","A","B","G","F","K","R"}

I have another array :

string [] subnames={"P","G","O"}

How can we check whether names array has any elements of subnames array.

In the above example "P" and "G" are there in names.

like image 512
palak mehta Avatar asked Jun 21 '12 13:06

palak mehta


2 Answers

The absolute simplest way would be to use the Enumerable.Intersect method. Then us the Any method on the result

bool containsValues = names.Intersect(subnames).Any();
like image 129
Fr33dan Avatar answered Oct 06 '22 00:10

Fr33dan


This will work too:

bool result = names.Any(subnames.Contains);

EDIT

This code may look incomplete but it actually works (method group approach).

like image 23
Maciej Avatar answered Oct 06 '22 01:10

Maciej