6

似乎这应该是一件容易的事,但我不知道如何用 LINQ 做到这一点。到目前为止,我能找到的唯一信息是关于循环赛的形式,这不是我想要的。我可能搜索错了。给定以下列表:

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

我如何对此进行排序(最好使用 linq),以便它以“循环”顺序出现,也就是说,在重复之前选择每个唯一项目一次。所以上面的列表会像这样出现(如果它按字母顺序出现并不重要,即使这个列表确实如此):

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

我知道我可以通过艰难的迭代来做到这一点,我只是希望有一些更简单的东西。有谁知道如何做到这一点?提前致谢!

4

3 回答 3

10
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();
于 2012-05-28T11:34:05.923 回答
0

我这样做过一次,挖出代码:

//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);
于 2012-05-28T11:34:15.640 回答
0

刚刚看到我写这篇文章时弹出了两个答案;哦,好吧,这是另一种方式:

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();
于 2012-05-28T11:58:08.043 回答