Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing a single item from an enumerable source when the items are equal

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.

like image 876
Bryan Boettcher Avatar asked Nov 29 '22 02:11

Bryan Boettcher


1 Answers

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.

like image 67
Amy B Avatar answered May 11 '23 00:05

Amy B