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

X89*_*89i 2 c# list distinct

有没有删除随之而来的值(即一个函数14, 14 -> 1412, 12 -> 12)?

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

List<string> foo = new List<string> { 12, 14, 14, 12, 12, 14 };
Run Code Online (Sandbox Code Playgroud)

到清单[12, 14, 12, 14]

fub*_*ubo 5

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

  • 这应该是公认的答案。 (2认同)
  • 很好,但在一般情况下,如果IEnumerable &lt;T&gt;不是*物化集合*,而是文件-File.ReadLines(“ c:\ myFile.txt”)`,那么您可以拥有* source.Any()的incidenttent *结果-首次实现;source.First()-第二个实现,而foreach(... source.Skip(1))-第三个。 (2认同)