Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting common values in two array issue using LINQ

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.

like image 519
Rajeev Kumar Avatar asked Oct 11 '13 11:10

Rajeev Kumar


People also ask

Can LINQ query work with Array?

Yes it supports General Arrays, Generic Lists, XML, Databases and even flat files. The beauty of LINQ is uniformity.

How to write LINQ select query in C#?

In a LINQ query, the first step is to specify the data source. In C# as in most programming languages a variable must be declared before it can be used. In a LINQ query, the from clause comes first in order to introduce the data source ( customers ) and the range variable ( cust ).


2 Answers

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);
like image 137
Tim Schmelter Avatar answered Sep 27 '22 22:09

Tim Schmelter


This will work:

list1.Where(x=>list2.Contains(x))
like image 28
Anarion Avatar answered Sep 27 '22 22:09

Anarion