我有一个序列。例如:
new [] { 10, 1, 1, 5, 25, 45, 45, 45, 40, 100, 1, 1, 2, 2, 3 }现在我必须在不改变整体顺序的情况下删除重复的值。对于上面的序列:
new [] { 10, 1, 5, 25, 45, 40, 100, 1, 2, 3 }如何使用LINQ做到这一点?
发布于 2012-05-26 22:00:12
var list = new List<int> { 10, 1, 1, 5, 25, 45, 45, 45, 40, 100, 1, 1, 2, 2, 3 };
List<int> result = list.Where((x, index) =>
{
return index == 0 || x != list.ElementAt(index - 1) ? true : false;
}).ToList();这将返回您想要的内容。希望这能帮上忙。
发布于 2012-05-26 22:00:00
var list = new List<int> { 10, 1, 1, 5, 25, 45, 45, 45, 40, 100, 1, 1, 2, 2, 3 };
var result = list.Where((item, index) => index == 0 || list[index - 1] != item);发布于 2012-05-26 20:10:30
您可以使用Contains和preserve
List<int> newList = new List<int>();
foreach (int n in numbers)
if (newList.Count == 0 || newList.Last() != n)
newList.Add(n);
var newArray = newList.ToArray();输出:
10、1、5、25、45、40、100、1、2、3
https://stackoverflow.com/questions/10766072
复制相似问题