IEnumerable<String> existedThings =
from mdinfo in mdInfoTotal select mdinfo.ItemNo;
IEnumerable<String> thingsToSave =
from item in lbXReadSuccess.Items.Cast<ListItem>() select item.Value;
Here are two IEnumerable
.
I want to check whether a value in existedThings
exist in thingsToSave
.
O.K. I can do that with 3 line code.
bool hasItemNo;
foreach(string itemNo in existedThings)
hasItemNo= thingsToSave.Contains(itemNo);
But, It looks dirty.
I just want to know if there is better solution.
int[] id1 = { 44, 26, 92, 30, 71, 38 };
int[] id2 = { 39, 59, 83, 47, 26, 4, 30 };
IEnumerable<int> both = id1.Intersect(id2);
foreach (int id in both)
Console.WriteLine(id);
//Console.WriteLine((both.Count() > 0).ToString());
Console.WriteLine(both.Any().ToString());
Look for the Enumerable.Intersect Method
The upvoted answers propose an algorithm that will have O(n^2) complexity if the IEnumerable wasn't derived from a class that implements ICollection<>. A Linq query for example. The Count() extension method then has to iterate all elements to count them. That's not cool. You only need to check if the result contains any elements:
bool hasItemNo = existedThings.Intersect(thingsToSave).Any();
The order matters btw, make the enumeration that you expect to have the smallest number of items the argument of Intersect().
You can use Intersect
to achieve this:
// puts all items that exists in both lists into the inBoth sequence
IEnumerable<string> inBoth = existedThings.Intersect(thingsToSave);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With