I need to intersect 2 arrays (List<T>) by keeping just the distinct elements and mix the elements of one array with the other like this:
A1 B1 C1 D1
W2 X2 Y2 Z2
=> A1 W2 B1 X2 C1 Y2 D1 Z2
A1 B1 A1 D1
W2 X2 Y2 Z2
=> A1 W2 B1 X2 Y2 D1 Z2 // repeating A1
A1 B1 A1 D1
Z2 X2 Y2 Z2
=> A1 Z2 B1 X2 Y2 D1 // repeating A1, Z2
A1 B1 C1 D1 E1
Z2 X2 Y2
=> A1 Z2 B1 X2 C1 Y2 D1 E1
What is the optimal LINQ query to do it?
An interleave extension method (replaces
Zip/SelectManyin Jon Skeets version). This may be a little faster and it includes the remaining of the longest list if the lists aren’t of equal length:And if you want distinct items, use:
This answer, of cause, doesn’t solve the uncertainty about
Distinctas described in comments to Jon Skeet´s answer. But it could be combined with Jon Skeet´s order preserving extension method.