I have two sorted lists as below:
var list1 = new List<int>() { 1, 1, 1, 2, 3 };
var list2 = new List<int>() { 1, 1, 2, 2, 4 };
I want the output to be: {1, 1, 2}
How to do this in C#? Is there a way using Linq?
I have two sorted lists as below:
var list1 = new List<int>() { 1, 1, 1, 2, 3 };
var list2 = new List<int>() { 1, 1, 2, 2, 4 };
I want the output to be: {1, 1, 2}
How to do this in C#? Is there a way using Linq?
The extra 1 means you can't use
Intersect
because it returns a set.Here's some code that does what you need:
While both @Austin Salonen's solution and @Enigmativity's solution work for any given lists, neither take advantage of OP's condition that the lists are sorted.
Given that both lists will be ordered we can do a search in
O(n + m)
time where n and m are the length of each list. Not entirely sure what the previous solutions big o performance is, but it's definitely slower thenO(n + m)
.Basically we just walk both lists, moving one or both enumerators based on a comparison check.
That's it!
results
will be an empty list if no matches are found. Note this assumes both lists are in ascending order. If it's descending, just flip the<
and>
operators.Use
Intersect
:I am late in answering this question, this might help future visitors.
This works nicely: