如何合并列表中的多个连续值?

How to merge multiple consecutive values in a list?

是否有删除结果值的函数(即 14, 14 -> 1412, 12 -> 12)?

以下列表([12, 14, 14, 12, 12, 14]):

List<string> foo = new List<string> { 12, 14, 14, 12, 12, 14 };

加入列表[12, 14, 12, 14]?

Linq 没有额外的库,但有 副作用 是一个 快速而肮脏的 ( prior 副作用很难看)解决办法:

  List<string> foo = new List<string> { "12", "14", "14", "12", "12", "14" };

  string prior = null;

  List<string> result = foo
    .Where((v, i) => i == 0 || v != prior)
    .Select(v => prior = v)
    .ToList();

一般情况下,您可能想要实现一个扩展方法:

  public static partial class EnumerableExtensions {  
    public static IEnumerable<T> DistinctSuccessive<T>(
      this IEnumerable<T> source, 
           IEqualityComparer<T> comparer = null) {
      // public method arguments validation
      if (null == source)
        throw new ArgumentNullException(nameof(source));

      // equals: either default or custom one 
      Func<T, T, bool> equals = (left, right) => null == comparer 
        ? object.Equals(left, right) 
        : comparer.Equals(left, right);

      bool first = true;
      T prior = default(T);

      foreach (var item in source) {
        if (first || !equals(item, prior))
          yield return item;

        first = false;
        prior = item;
      }
    }
  }

然后

  List<string> result = foo
    .DistinctSuccessive()
    .ToList();

我个人更喜欢@fubo 的回答,但只是为了表明有更多变体:

var data = new[] { 12, 14, 14, 12, 12, 14 };
var result = data.Aggregate(new List<int>(), (a, e) => { if (a.FirstOrDefault() != e) a.Insert(0, e); return a; });
result.Reverse(); // we builded a list in a back order, so reverse it!

接近foreach

public static IEnumerable<T> DistinctByPrevious<T>(List<T> source)
{
    if (source != null && source.Any())
    {
        T prev = source.First();
        yield return prev;
        foreach (T item in source.Skip(1))
        {
            if (!EqualityComparer<T>.Default.Equals(item, prev))
            {
                yield return item;
            }
            prev = item;
        }
    }
}