LINQ通过“循环"顺序进行订购. [英] LINQ order by "round robin"

查看:87
本文介绍了LINQ通过“循环"顺序进行订购.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看起来像这样应该很容易,但是我不知道如何使用LINQ来做到这一点.到目前为止,我唯一能找到的信息是关于循环锦标赛的格式,这不是我想要的.我可能搜索错了.给出以下列表:

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" };

我该如何对其进行排序(最好使用linq),以使其以循环"顺序出现,也就是说,在重复之前,请选择每个唯一项.因此,上面的列表将这样显示出来(即使此列表确实按字母顺序显示也并不重要):

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!

推荐答案

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

这篇关于LINQ通过“循环"顺序进行订购.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆