1

This should be pretty simple but LINQ's Contains() doesn't take an array. I have 2 arrays of strings

e.g.1 {"The","quick","Brown"}

And I want to compare another array of strings and return true if any string appears in it.

e.g.2 {"This","doesnt","quick","Work"}

So "quick" appears in the 2nd array.

Is it best making the first string joined comma delimited so it looks like "The, quick , Brown" and then running contains in a loop against it?

I'm sure this can be done properly using LINQ.

3 Answers 3

6
bool exists = first.Intersect(second).Any();

Or, if you want to know what the common words actually are:

var commonWords = first.Intersect(second);

foreach (string s in commonWords)
{
    Console.WriteLine(s);
}
Sign up to request clarification or add additional context in comments.

Comments

2
var first = new[] {"the", "quick", "brown"};
var second = new[] {"This","doesnt","quick","Work"};

var found = from a in first
            from b in second
            where a == b
            select a;

if(found.Any())
    return true;

4 Comments

This is O(n*m) whereas using Intersect should be O(n+m). It won't matter for examples like this, but could make a big difference for larger sequences.
@Jon: Using Intersect is more efficient (although probably not noticeably so if the sequences are small).
@LukeH: Ok great, how would this work for case-insensitivity too?
@Jon: Intersect can take an IEqualityComparer<T> to handle that. For example, bool exists = first.Intersect(second, StringComparer.OrdinalIgnoreCase).Any(); or similar. msdn.microsoft.com/en-us/library/bb355408.aspx
0

I think I'd use:

var query = from a in first
            where b.Contains(a)
            select a;

var isThereAMatch = query.Any();

If the lists were very large and matches were likely to be sparse, then I might optimise this by using a lookup/hashset for b.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.