有没有删除随之而来的值(即一个函数14, 14 -> 14,12, 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]?
用的方法 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)