Linq Distinct仅在下一行匹配

Jon*_*rdo 6 .net c# linq

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

365.00
370.00
369.59
365.00
365.00 -> match with previous item
365.00 -> match with previous item
Run Code Online (Sandbox Code Playgroud)

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

365.00
370.00
369.59
365.00
Run Code Online (Sandbox Code Playgroud)

我试过了:

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

结果:

365.00
370.00
369.59
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Eri*_*ert 7

另一种方法:

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

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

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

  • @displayName:很高兴帮忙.我经常总结Brian的观点的方式是**查询表达式代表一个问题,而不是答案**.枚举查询实际上会询问问题; 每次问题时问题的答案是否相同取决于问题是什么以及你问的是谁. (5认同)