Getting common values ​​in two issues using LINQ

I have two arrays:

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

When I try to get common elements from these two arrays using the following code

  var listCommon = list1.Intersect(list2); 

It gives me a result like this

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

But I want him to return like this:

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

This value shields the last value of the empty string at the intersection.

+6
source share
2 answers

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

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

which is not so effective. This may be an optimization:

 var l2Lookup = new HashSet<string>(list2); var listCommon = list1.Where(l2Lookup.Contains); 
+9
source

This will work:

 list1.Where(x=>list2.Contains(x)) 
+5
source

Source: https://habr.com/ru/post/955760/


All Articles