5

I have two arrays say

var list1 = string[] {"1", "2", "3", "4", "", ""};
var list2 = string[] {"2", "3", "4","",""};

When i try to get common items form these two array using following code

 var listCommon = list1.Intersect(list2);

It gives me result like this

string[] {"2", "3", "4", ""}

But i want it should return like this

string[] {"2", "3", "4", "", ""}

It is escaping last empty string value while intersecting.

Rajeev Kumar
  • 4,901
  • 8
  • 48
  • 83

2 Answers2

9

Set methods like Intersect or Except remove duplicates from each collection. I assume you want something like this instead:

var listCommon = list1.Where(list2.Contains);

which is not as efficient. This could be an optimization:

var l2Lookup = new HashSet<string>(list2);
var listCommon = list1.Where(l2Lookup.Contains);
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • Interesting. I notice you are less keen to close/delete questions when you are raking in the rep from it, Tim... – David Arno Oct 11 '13 at 11:47
  • @DavidArno: I have no idea what you're talking about. I have not noticed the duplicate vote until now. But even if, do i get a downvote from you because i answer a question that you have voted to close ? – Tim Schmelter Oct 11 '13 at 11:49
  • Of course if the second list only contains one empty string this would still return two empty strings, because the first list has two. Not sure if that's exactly what the OP wants, but the other way would definitely be more complex. – juharr Oct 11 '13 at 11:52
7

This will work:

list1.Where(x=>list2.Contains(x))
Anarion
  • 2,406
  • 3
  • 28
  • 42