c# – Linq区别仅在下一行匹配

我有一个包含以下信息的数据表:

365.00
370.00
369.59
365.00
365.00 -> match with previous item
365.00 -> match with previous item

我只需要删除下一个匹配的项目,如下所示:

365.00
370.00
369.59
365.00

我试过了:

(from articlespricehistory in dt.AsEnumerable()
select new
{
   articlepricehistory_cost = articlespricehistory.Field<Double>("articlepricehistory_cost")
})
.DistinctBy(i => i.articlepricehistory_cost)
.ToList();

结果:

365.00
370.00
369.59

有任何想法吗?

另一种方法:

public static IEnumerable<T> MyDistinct<T>(this IEnumerable<T> items) 
{
    T previous = default(T);
    bool first = true;
    foreach(T item in items)
    {
        if (first || !Equals(previous, item)) 
        {
            first = false;
            previous = item;
            yield return item;
        }
    }
} 

或者,根据要求,使用选择器

public static IEnumerable<T> MyDistinct<T, U>(this IEnumerable<T> items, Func<T, U> selector) 
{
    U previous = default(U);
    bool first = true;
    foreach(T item in items)
    {
        U current = selector(item);
        if (first || !Equals(previous, current)) 
        {
            first = false;
            previous = current;
            yield return item;
        }
    }
} 

转载注明原文:c# – Linq区别仅在下一行匹配 - 代码日志