Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ order by "round robin"

Seems like this should be an easy task but I can't figure out how to do this with LINQ. The only information I've been able to find so far is regarding the round robin tournament format, which isn't what I'm after. I may be searching wrong. Given the following list:

var items [] { "apple", "banana", "banana", "candy", "banana", "fruit", "apple" };

How can I sort this (preferably using linq) so that it comes out in "round robin" order, that is, select each unique item once before repeats. So the above list would come out like this (It's not important if it comes out in alphabetical order, even though this list does):

var sorted [] { "apple", "banana", "candy", "fruit", "apple", "banana", "banana" };

I know I can do this by iterating over it the hard way, I was just hoping for something easier. Does anyone have any insight how to do this? Thanks in advance!

like image 227
Eric Avatar asked May 28 '12 11:05

Eric


1 Answers

var sorted = items.GroupBy(s => s)
    .SelectMany(grp => grp.Select((str, idx) => new { Index = idx, Value = str }))
    .OrderBy(v => v.Index).ThenBy(v => v.Value)
    .Select(v => v.Value)
    .ToArray();
like image 155
Lee Avatar answered Sep 28 '22 08:09

Lee