使用linq从List <T>中删除连续重复项

Ed *_*d W 7 c# linq

我正在寻找一种方法来防止重复列表中的项目但仍保留订单.例如

1, 2, 3, 4, 4, 4, 1, 1, 2, 3, 4, 4 
Run Code Online (Sandbox Code Playgroud)

应该成为

1, 2, 3, 4, 1, 2, 3, 4
Run Code Online (Sandbox Code Playgroud)

我使用for循环非常优雅地完成它,检查下一项如下

    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;
    }
Run Code Online (Sandbox Code Playgroud)

是否有更优雅的方式来做到这一点,最好是LINQ?

Ser*_*kiy 11

您可以创建扩展方法:

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;
        }
    }        
}
Run Code Online (Sandbox Code Playgroud)

用法:

var result = items.RemoveSequentialRepeats().ToList();
Run Code Online (Sandbox Code Playgroud)

  • 您可以为其创建一个重载,它也允许指定自定义比较器. (2认同)
  • @KingKing - 这是正常的'foreach`,只是特殊的外壳第一元素.还显示了如何使用`Equals`进行适用于所有类型的泛型比较. (2认同)
  • @KingKing LINQ也使用委托,但委托不是LINQ :) (2认同)

Kin*_*ing 5

你也可以使用纯LINQ:

List<int> list = new List<int>{1, 2, 3, 4, 4, 4, 1, 1, 2, 3, 4, 4};
var result = list.Where((x, i) => i == 0 || x != list[i - 1]);
Run Code Online (Sandbox Code Playgroud)


Zah*_*med 2

检查新列表的最后一个和当前项目是否不相同,然后添加到新列表:

List<string> results = new List<string>();
results.Add(array.First());
foreach (var element in array)
{
    if(results[results.Length - 1] != element)
        results.Add(element);
}
Run Code Online (Sandbox Code Playgroud)

或使用 LINQ:

List<int> arr=new List<int>(){1, 2, 3, 4, 4, 4, 1, 1, 2, 3, 4, 4 };
List<int> result = new List<int>() { arr.First() };
arr.Select(x =>
               {
                if (result[result.Length - 1] != x) result.Add(x);
                    return x;
               }).ToList();
Run Code Online (Sandbox Code Playgroud)

对空对象进行适当的验证。