除去列表与LT连续重复项目; T>使用LINQ [英] Removing sequential repeating items from List<T> using linq

查看:181
本文介绍了除去列表与LT连续重复项目; T>使用LINQ的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来阻止列表中的重复项目,但仍维持秩序。
为例

I'm looking for a way to prevent repeating items in a list but still preserve the order. For example

1, 2, 3, 4, 4, 4, 1, 1, 2, 3, 4, 4 

应成为

1, 2, 3, 4, 1, 2, 3, 4

我这相当粗暴使用 循环,检查下一个项目做如下

I've done it quite inelegantly using a for loop, checking the next item as follows

    public static List<T> RemoveSequencialRepeats<T>(List<T> input) 
    {
        var result = new List<T>();

        for (int index = 0; index < input.Count; index++)
        {
            if (index == input.Count - 1)
            {
                result.Add(input[index]);
            }
            else if (!input[index].Equals(input[index + 1]))
            {
                result.Add(input[index]);
            }
        }

        return result;
    }



有没有更优雅的方式来做到这一点,最好使用LINQ?

Is there a more elegant way to do this, preferably with LINQ?

推荐答案

您可以创建扩展方法:

public static IEnumerable<T> RemoveSequentialRepeats<T>(
      this IEnumerable<T> source)
{
    using (var iterator = source.GetEnumerator())
    {
        var comparer = EqualityComparer<T>.Default;

        if (!iterator.MoveNext())
            yield break;

        var current = iterator.Current;
        yield return current;

        while (iterator.MoveNext())
        {
            if (comparer.Equals(iterator.Current, current))
                continue;

            current = iterator.Current;
            yield return current;
        }
    }        
}



用法:

Usage:

var result = items.RemoveSequentialRepeats().ToList();

这篇关于除去列表与LT连续重复项目; T&GT;使用LINQ的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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