Mehdi LAMRANI
Mehdi LAMRANI

Reputation: 11597

How to Check if strings in an array contain strings from another array

Main Question :
Ok guys, here is the situation, let's consider 2 string arrays :

string foo = { "Roses are #FF0000" , "Violets are #0000FF", "Paint it #000000"}
string bar = { "Guns", "Roses", "Violets"}

What is the "fewest code lines" way to retrieve strings in foo containing strings in bar ?
(i.e, in this case, the 2 first elements of foo)

Of course I want to avoid doing all the logic "by hand" as I am sure Linq is more efficient with the intersect feature, but I do not know how to use it to perform this precise task.

TieBreakers :
1 - What if foo contains strings that contain more that one element of bar,

string foo = { "Roses are #FF0000" , "Violets are #0000FF", "Paint it #000000"}
string bar = { "Roses", "Violets", "are"}

And I want to avoid duplicates ?

2 - What if I have 2 "bar" arrays that I want to check against one foo array ?
Is it more efficient to merge bar1 and bar2 or to perform the filter with bar1 first and then with bar2 ?


Thanx and have fun answering :-)

Upvotes: 5

Views: 1434

Answers (3)

Blindy
Blindy

Reputation: 67372

Assuming the string in your description is your teacher's typo,

var result=foo.Where(w=>bar.Any(iw=>w.Contains(iw)));

I'm not sure what duplicates you mean, that will only show elements in foo once no matter how many times they appear in bar.

As for the 2nd tie breaker, all you have to do is something like this:

var result=foo.Where(w=>bar1.Any(iw=>w.Contains(iw))||bar2.Any(iw=>w.Contains(iw)));

Upvotes: 2

Albin Sunnanbo
Albin Sunnanbo

Reputation: 47038

string[] foo = new string[] { "Roses are #FF0000", "Violets are #0000FF", "Paint it #000000" };
string[] bar = new string[] { "Guns", "Roses", "Violets" };

var matches = from f in foo
                where bar.Any(b => f.Contains(b))
                select f;

foreach (var m in matches)
    Console.WriteLine(m);

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1499950

LINQ works well, yes:

var mixed = foo.Where(x => bar.Any(y => x.Contains(y));

Note that you'll still only see each element of foo once, if at all.

If you have multiple bar arrays, you can use:

var mixed = foo.Where(x => bar1.Concat(bar2)
                               .Any(y => x.Contains(y));

Upvotes: 6

Related Questions