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.
Yes it supports General Arrays, Generic Lists, XML, Databases and even flat files. The beauty of LINQ is uniformity.
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 ).
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);
This will work:
list1.Where(x=>list2.Contains(x))
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