LINQ order by “round robin”

久未见 提交于 2019-12-05 09:00:27
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();

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);

Just saw that two answers popped up while I was writing this; oh 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();
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!