Reputation: 706
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.
Upvotes: 15
Views: 36178
Reputation: 1
Another way: I share both how to check one (several) word parts and all
string[] subnames = { "P", "G", "O" };
bool all = subnames.All(s => names.Contains(s));
bool anyInBoth = subnames.All(s => names.Contains(s));
Upvotes: 0
Reputation: 132
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;
}
Upvotes: 0
Reputation: 7961
This will work too:
bool result = names.Any(subnames.Contains);
EDIT
This code may look incomplete but it actually works (method group approach).
Upvotes: 10
Reputation: 4325
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();
Upvotes: 18
Reputation: 50493
You could use some Linq and then use Intersect
var commonNames = names.Intersect(subnames);
Upvotes: 4
Reputation: 5002
To check if any:
bool anyInBoth = names.Intersect(subnames).Any();
To get the ones in both:
IEnumerable<string> inBoth = names.Intersect(subnames);
Upvotes: 2
Reputation: 3605
Linq is the simplest I think:
from n1 in names
join n2 in subnames on n1 equals n2
select n1;
Upvotes: 0
Reputation: 37533
Here is a Linq solution that should give you what you need:
names.Any(x => subnames.Contains(x))
Upvotes: 36