Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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 :-)

like image 472
Mehdi LAMRANI Avatar asked May 16 '11 11:05

Mehdi LAMRANI


People also ask

How do you check if an array contains an element from another array?

Use the inbuilt ES6 function some() to iterate through each and every element of first array and to test the array. Use the inbuilt function includes() with second array to check if element exist in the first array or not. If element exist then return true else return false.

How do you check if a string contains a string from an array?

You can use the includes() method in JavaScript to check if an item exists in an array. You can also use it to check if a substring exists within a string. It returns true if the item is found in the array/string and false if the item doesn't exist.

How do I check if two arrays have the same contents?

The Arrays. equals() method checks the equality of the two arrays in terms of size, data, and order of elements. This method will accept the two arrays which need to be compared, and it returns the boolean result true if both the arrays are equal and false if the arrays are not equal.


1 Answers

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));
like image 138
Jon Skeet Avatar answered Oct 16 '22 16:10

Jon Skeet