【问题标题】:remove contiguous duplicates in the sequence of objects [duplicate]删除对象序列中的连续重复项[重复]
【发布时间】: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,谢谢,它解决了问题

标签: c# .net algorithm


【解决方案1】:

试试这个:

List<int> newList = new List<int>();
foreach (var item in list.Where(c => newList.Count == 0 || newList.Last() != c))
{
    newList.Add(item); // 1,2,3,2,1 will add to newList
}

【讨论】:

    【解决方案2】:

    我喜欢扩展方法的想法:

    public static IEnumerable<T> RemoveContiguousDuplicates<T>(this IEnumerable<T> items) where T: IEquatable<T>
    {
        bool init = false;
        T prev = default(T);
    
        foreach (T item in items)
        {
            if (!init)
                init = true;
            else if (prev.Equals(item))
                continue;
    
            prev = item;
            yield return item;
        }
    }
    

    然后,当然要使用它:

    var singles = list.RemoveContiguousDuplicates().ToList();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-12
      • 1970-01-01
      • 2020-06-12
      • 1970-01-01
      • 2011-07-23
      • 2018-12-01
      • 2012-10-09
      • 1970-01-01
      相关资源
      最近更新 更多