CodeNinja
CodeNinja

Reputation: 3278

find if there is a common string between 2 list of strings using linq

I have two Lists of strings:

List<string> lotterynumber;
List<string> lotterywinningnumber;

I want to see if a lotterynumber is within the lotterywinningnumber.

I am using a foreach loop right now:

bool b = false;
foreach(string s in lotterynumber)
{
    if(lotterywinningnumber.contains(s))
    {
        b= true;
    }
}

Is there a way I can do it in Linq?

Upvotes: 0

Views: 2690

Answers (2)

Matyas
Matyas

Reputation: 1172

There is a way, but the efficiency will be the same: O(n).

Use Any

bool b = lotterynumber.Any(a => lotterywinningnumber.Contains(a));

Upvotes: 2

johnnyRose
johnnyRose

Reputation: 7490

You can do this using Enumerable.Intersect. It will return a new Enumerable containing the items that exist in both collections.

var lotteryNumbers = new List<string>() { "1", "2", "3" };
var lotteryWinningNumbers = new List<string>() { "2", "3", "5" };
var numbersInBoth = lotteryNumbers.Intersect(lotteryWinningNumbers); // { "2", "3" }

From MSDN:

The intersection of two sets A and B is defined as the set that contains all the elements of A that also appear in B, but no other elements. When the object returned by this method is enumerated, Intersect enumerates first, collecting all distinct elements of that sequence. It then enumerates second, marking those elements that occur in both sequences. Finally, the marked elements are yielded in the order in which they were collected.

The benefit to using Intersect is that it will return the values that exist in both collections, instead of just a Boolean value.

Obviously, if a Boolean value is what you need, you just have to check if the resulting collection contains any elements:

bool contains = lotteryNumbers.Intersect(lotteryWinningNumbers).Any();

Upvotes: 5

Related Questions