LINQ order from "round robin"

It seems like this should be a simple task, but I can't figure out how to do this with LINQ. The only information that I have been able to find so far concerns the format of the tournament with a round-robin tournament, which is not what I need. Maybe I'm 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 the order of "round robin", i.e. Each individual item was selected once before repeating. So the above list will come out as follows (it doesn't matter if it comes out in alphabetical order, even if this list does):

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

I know that I can do this, iterate along this difficult path, I just hoped for something simpler. Does anyone know how to do this? Thanks in advance!

+6
source share
3 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(); 
+8
source

I did this once, dug up the code:

 //Originially written for lists, all you need is prepend a .ToList() where needed to apply this to an array List<string> src = new List<string> { "string1", "string2" }; //source List<string> dst = new List<string>(); dst.AddRange(src.Distinct()); dst.ForEach(d => src.RemoveAt(src.FindIndex(i => i.Equals(d)))); //remove the first occurrence of each distinct element dst.AddRange(src); 
0
source

I just saw that two answers appeared when I wrote this; well, here is another way:

 var items [] { "apple", "banana", "banana", "candy", "banana", "fruit", "apple" }; var uniqueItems = items.Distinct().OrderBy(item => item); // alphabetical orderBy is optional var duplicateItems = items .GroupBy(item => item) .SelectMany(group => group.Skip(1)) .OrderBy(item => item); // alphabetical orderBy is optional; var sorted = uniqueItems.Append( duplicateItems ).ToArray(); 
0
source

Source: https://habr.com/ru/post/916837/


All Articles