看起来这应该是一件容易的事,但我无法弄清楚如何使用LINQ做到这一点。 我已经能够迄今为止发现的唯一信息是关于循环赛比赛的形式,这是不是我后。 我可能是错误的搜索。 鉴于以下列表:
var items [] { "apple", "banana", "banana", "candy", "banana", "fruit", "apple" };
我怎样才能解决这(最好使用LINQ),因此它在“循环”为了出来,也就是重复前一次选择每一个独特的项目。 所以上面的列表会出来这样的(如果按字母顺序排列出来,尽管这个名单确实这并不重要):
var sorted [] { "apple", "banana", "candy", "fruit", "apple", "banana", "banana" };
我知道我可以通过遍历它的硬盘的方式做到这一点,我只是希望的东西更容易。 有没有人有任何见解如何做到这一点? 提前致谢!
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();
我这样做一次,挖出的代码:
//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);
刚看到这两个答案弹出我在写这一点的同时, 哦,这里是另一种方式:
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();