6

Is it possible to use the LEAD or LAG SQL functions from C#?

My preference of method is:

  1. Linq to SQL
  2. Entity Framework
  3. Dynamic Linq
  4. SQLFunctions class
  5. Manual TSQL via a SQLCommand

I know it can be done via method 5, but what about 1 through 4?

Felix Pamittan
  • 31,544
  • 7
  • 41
  • 67
OrdinaryOrange
  • 2,420
  • 1
  • 16
  • 25
  • 1
    http://stackoverflow.com/a/21767411/1132334 would imply that 1 and 3 are not possible (yet). But this answer is already more than two years old so research in the most recent .NET framework seems worth the effort – Cee McSharpface May 23 '16 at 07:29

2 Answers2

3

Look into the MoreLinq project (on github): http://morelinq.github.io

There, Lead and Lag are implemented as extensions:

public static IEnumerable<TResult> Lag<TSource, TResult>(
    this IEnumerable<TSource> source,
    int offset,
    TSource defaultLagValue,
    Func<TSource, TSource, TResult> resultSelector
)

reference: https://morelinq.github.io/2.0/ref/api/html/M_MoreLinq_MoreEnumerable_Lag__2_1.htm

EDIT: This is Linq to Objects only. So when applied to an SQL data source, it would fetch all rows and then do the computation outside the database. This is not what the OP expects.

Research results say "no, it is not possible" for items 1,2,3 and 4:

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Cee McSharpface
  • 8,493
  • 3
  • 36
  • 77
  • I did look at that, but it appears to be just for linq to objects. I just downloaded the latest beta to prove, and yep, pulls the entire table from SQL before then performing the lag/lead in memory. – OrdinaryOrange May 23 '16 at 12:33
1

Awesome lib linq2db https://github.com/linq2db/linq2db supports Window-Functions with LEAD and LAG:

    from p in db.Parent
    join c in db.Child on p.ParentID equals c.ParentID
    select new
    {
        Diff = Sql.Ext
                  .Lag(x.time, Sql.Nulls.None)
                  .Over()
                  .PartitionBy(p.time.Date)
                  .OrderBy(p.time)
                  .ToValue()
    };
Brains
  • 594
  • 1
  • 6
  • 18