Selecting every nth row using LINQ

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

For shorter time and time intervals, I can just read the data and generate charts:

var mydata = entity.DataLogSet.Where(dt => dt.DateTime > dateLimit);

But we want to implement a function in which you can quickly “zoom out” from charts to include larger time intervals (last 5 days, last month, last 6 months, last 10 years, etc. etc.)

We do not want to display each data point for this. We want to use a sample data, by which I mean something like this -

  • Last 5 days : indicate each data point in the table
  • Last Month : List every tenth data point in the table.
  • Last 6 months : chart every 100 data points

The number of data points and chart names are just examples. I need a way to select only the string "nth" from the database.

+4
source share
1 answer

You can use Select Overload, which includes the index of an enumeration element. 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);

OrderBy, , -

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);

, juharr, Entity Framework. - - -

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);

a ToArray(). , , , n- .

+2

Source: https://habr.com/ru/post/1677022/


All Articles