Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check existense between two IEnumerable

Tags:

c#

.net

linq

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.

like image 675
Sungguk Lim Avatar asked Jun 10 '10 11:06

Sungguk Lim


3 Answers

 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

like image 126
VMAtm Avatar answered Oct 21 '22 13:10

VMAtm


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().

like image 25
Hans Passant Avatar answered Oct 21 '22 13:10

Hans Passant


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);
like image 4
Fredrik Mörk Avatar answered Oct 21 '22 11:10

Fredrik Mörk