Lets say I have an enumerable source, that looks like this:
IEnumerable<string> source = new [] { "first", "first", "first", "second" };
I want to be able to construct a LINQ statement that will return this:
"first", "first", "second"
Notice how only one of the firsts is gone. I don't care which one, because in my case all 3 "first"s are considered equal. I've tried source.Except(new [] { "first" })
but that strips all instances out.
source
.GroupBy(s => s)
.SelectMany(g => g.Skip(1).DefaultIfEmpty(g.First()))
For each group, skip the first element of the group and return the rest - unless that would return none... in that case, return the first element of the group.
source
.GroupBy(s => s)
.SelectMany(g => g.Take(1).Concat(g.Skip(2)))
For each group, take the first element, and take from the third element on - always skipping the second element.
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