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

I have an array of strings: for example:

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

I have another array:

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

How to check if an array of names has any elements of an array of subtasks.

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

+6
source share
7 answers

Here is a Linq solution that should give you what you need:

 names.Any(x => subnames.Contains(x)) 
+21
source

An absolutely simple way would be to use the Enumerable.Intersect method. Then we have Any method for the result

 bool containsValues = names.Intersect(subnames).Any(); 
+10
source

This will work too:

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

EDIT

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

+7
source

You can use some Linq and then use Intersect

 var commonNames = names.Intersect(subnames); 
+3
source

To check if there are:

 bool anyInBoth = names.Intersect(subnames).Any(); 

To get them in both:

 IEnumerable<string> inBoth = names.Intersect(subnames); 
+2
source

Linq is the simplest thing I think:

 from n1 in names join n2 in subnames on n1 equals n2 select n1; 
0
source
 bool DiziIcindeDiziVarMi(string[] parent, string[] child) { int say = 0; for (var i = 0; i < child.Length; i++) for (var j = 0; j < parent.Length; j++) if (child[i] == parent[j]) say++; return say == child.Length; } 
0
source

All Articles