0

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?

1
  • 2
    Is it 2 strings or 2 List<string>? Commented Sep 11, 2015 at 17:52

2 Answers 2

5

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();
Sign up to request clarification or add additional context in comments.

1 Comment

bool contains = lotteryNumbers.Intersect(lotteryWinningNumbers).Any() is a better choice that allows early short-circuitting.
2

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

Use Any

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

3 Comments

The efficiency will not necessarily be the same. In his example, he is iterating through each item in the collection. Any stops as soon as it finds an element which satisfies the condition. From the MSDN docs: The enumeration of source is stopped as soon as the result can be determined. The Big O runtime, however, will be the same on the average case. Both are O(n).
I agree, that is what I meant. - You are true, that I wasn't precise enough, when I didn't say, that I mean asymptotically. - Which is what is usually meant when talking about time consumption of algorithms.
It's the same if the OP added a break inside of the if.

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.