【发布时间】:2016-01-19 09:07:36
【问题描述】:
假设我们有对象列表
List<int> list = new List<int>() { 1,1,1,2,3,3,3,2,2,2,1,1 };
获取以下结果列表最优雅的方法是什么?
{1,2,3,2,1}
【问题讨论】:
-
假设您的列表包含可以使用Distinct() 的原始类型。例如:
list.Distinct().ToList();。如果您的列表包含复杂类型,您需要将其传递给您的类型实现的IEqualityComparer -
@sstan 请更好地阅读我的问题并删除“标记为重复”或提供有效答案
-
您想要的结果
{1,2,3,2,1}与您的要求remove duplicates in the sequence of objects不匹配,这将根据您的数据集为您提供1, 2, 3的结果。 -
你可以使用类似 var requiredList = list.Where((value, index) => index == 0 || value != list.ElementAt(index - 1));
-
@arunlalam,谢谢,它解决了问题