Can I use LINQ to retrieve only “on change” values?

前端 未结 5 829
死守一世寂寞
死守一世寂寞 2021-01-22 20:36

What I\'d like to be able to do is construct a LINQ query that retrieved me a few values from some DataRows when one of the fields changes. Here\'s a contrived example to illus

5条回答
  •  广开言路
    2021-01-22 21:22

    This is one of those instances where the iterative solution is actually better than the set-based solution in terms of both readability and performance. All you really want Linq to do is filter and pre-sort the list if necessary to prepare it for the loop.

    It is possible to write a query in SQL Server (or various other databases) using windowing functions (ROW_NUMBER), if that's where your data is coming from, but very difficult to do in pure Linq without making a much bigger mess.


    If you're just trying to clean the code up, an extension method might help:

    public static IEnumerable Changed(this IEnumerable items,
        Func equalityFunc)
    {
        if (equalityFunc == null)
        {
            throw new ArgumentNullException("equalityFunc");
        }
        T last = default(T);
        bool first = true;
        foreach (T current in items)
        {
            if (first || !equalityFunc(current, last))
            {
                yield return current;
            }
            last = current;
            first = false;
        }
    }
    

    Then you can call this with:

    var changed = rows.Changed((r1, r2) =>
        r1.Field("Observation") == r2.Field("Observation"));
    

提交回复
热议问题