在列表中查找连续的重复项 [英] Find continuous duplicates in a List

查看:64
本文介绍了在列表中查找连续的重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多方法可以找到列表中的重复项,是否有任何方法可以找到列表中的连续重复项.

There are loads of ways to find to find Duplicates in a list, is There any way to find continuous duplicates in a List.

例如

List<string> stringList = new List<string>();
stringList.Add("Name1");
stringList.Add("Name2");
stringList.Add("Name1");

除了

stringList.Add("Name1");
stringList.Add("Name1");
stringList.Add("Name2"); 

应返回1个条目

这将返回重复项.

 var q = listString.GroupBy(x => x)
         .Select(g => new { Value = g.Key, Count = g.Count() })
         .OrderByDescending(x => x.Count);

推荐答案

为什么不存储最后一项?像这样

Why not just store the last item? Something like this

public static partial class EnumerableExtensions { 
  // Simplest; IEquatable<T> for advanced version
  public static IEnumerable<T> Continuous<T>(this IEnumerable<T> source) {
    if (null == source)
      throw new ArgumentNullException("source");  

    T lastItem = default(T);
    Boolean first = true;

    foreach (var item in source) {
      if (first) {
        lastItem = item;
        first = false;
      }
      else if (Object.Equals(item, lastItem)) 
        yield return item;
      else
        lastItem = item; 
    }
  }  
}

然后

List<string> stringList = new List<string>() {
  "Name1",
  "Name1",
  "Name2",
};

var contDups = stringList
  .Continuous() 
  .ToList();

这篇关于在列表中查找连续的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆