SQL Lead and Lag functions from C# code

前端 未结 2 1743
栀梦
栀梦 2021-01-14 01:02

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

My preference of method is:

  1. Linq to SQL
  2. Entity Framewor
2条回答
  •  借酒劲吻你
    2021-01-14 01:36

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

    There, Lead and Lag are implemented as extensions:

    public static IEnumerable Lag(
        this IEnumerable source,
        int offset,
        TSource defaultLagValue,
        Func 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:

    • LEAD and LAG came about in SQL Server 2012, but the highest version of SQL server that the newest version of Linq to SQL (Framework 4.6.1) targets with version specific code, is 2008: http://referencesource.microsoft.com/#System.Data.Linq/SqlClient/SqlProvider.cs,2fac3481a656764b
    • Entity framework: nope, sorry.
    • MSDN hints that sequence functions generally have limited support: https://msdn.microsoft.com/de-de/library/bb882656(v=vs.100).aspx
    • there is no hint that SqlFunctions would provide Lead, Lag, or something similar: https://msdn.microsoft.com/en-us/library/system.data.objects.sqlclient.sqlfunctions(v=vs.110).aspx

提交回复
热议问题