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.

4
  • Why would 1 be returned? Commented Oct 11, 2013 at 11:38
  • "1" is not a common item Commented Oct 11, 2013 at 11:38
  • 2
    Duplicate of stackoverflow.com/questions/2180054/… Commented Oct 11, 2013 at 11:39
  • 1
    @DavidArno Actually that question is a little different. That question would expect to get {"2", "2", "3", "3, "4", "4", "", "", "", ""} for the example given here. Commented Oct 11, 2013 at 11:55

2 Answers 2

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

3 Comments

Interesting. I notice you are less keen to close/delete questions when you are raking in the rep from it, Tim...
@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 ?
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.
7

This will work:

list1.Where(x=>list2.Contains(x))

3 Comments

Too bad, i'm too late )
But your answer is better :) I cant understood what meens "list1.Where(l2Lookup.Contains)" in top answer. But your answer made it clear. Thank you @Anarion
@Andrey Rybalkin Keep in mind that Solution in answer by Tim Schmelter is way more efficient, because it's much faster to search in HashSet.

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.