Fetch every nth row with LINQ

前端 未结 1 875
臣服心动
臣服心动 2021-01-18 15:47

We have a table in our SQL database with historical raw data I need to create charts from. We access the DB via Entity Framework and LINQ.

For smaller datetime inter

相关标签:
1条回答
  • 2021-01-18 16:22

    You can use the Select overload that includes the item index of enumerations. Something like this should do the trick --

    var data = myDataLogEnumeration.
            Select((dt,i) => new { DataLog = dt, Index = i }).
            Where(x => x.Index % nth == 0).
            Select(x => x.DataLog);
    

    If you need to limit the query with a Where or sort with OrderBy, you must do it before the first Select, otherwise the indexes will be all wrong --

    var data = myDataLogEnumeration.
            Where(dt => dt.DateTime > dateLimit).
            OrderBy(dt => dt.SomeField).
            Select((dt,i) => new { DataLog = dt, Index = i }).
            Where(x => x.Index % nth == 0).
            Select(x => x.DataLog);
    

    Unfortunately, as juharr commented, this overload is not supported in Entity Framework. One way to deal with this is to do something like this --

    var data = entity.DataLogSet.
            Where(dt => dt.DateTime > dateLimit).
            OrderBy(dt => dt.SomeField).
            ToArray().
            Select((dt,i) => new { DataLog = dt, Index = i }).
            Where(x => x.Index % nth == 0).
            Select(x => x.DataLog);
    

    Note the addition of a ToArray(). This isn't ideal though as it will force loading all the data that matches the initial query before selecting only every nth row.

    0 讨论(0)
提交回复
热议问题