palak mehta
palak mehta

Reputation: 706

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

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

Answers (8)

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

Fatih Topcu
Fatih Topcu

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

Maciej
Maciej

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

Fr33dan
Fr33dan

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

Gabe
Gabe

Reputation: 50493

You could use some Linq and then use Intersect

var commonNames = names.Intersect(subnames);

Upvotes: 4

Chris Snowden
Chris Snowden

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

Steve Campbell
Steve Campbell

Reputation: 3605

Linq is the simplest I think:

from n1 in names
join n2 in subnames on n1 equals n2
select n1;

Upvotes: 0

Joel Etherton
Joel Etherton

Reputation: 37533

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

names.Any(x => subnames.Contains(x))

Upvotes: 36

Related Questions