LINQ to SQL Every Nth Row From Table

前端 未结 6 1558
情歌与酒
情歌与酒 2020-12-09 17:30

Anybody know how to write a LINQ to SQL statement to return every nth row from a table? I\'m needing to get the title of the item at the top of each page in a paged data gr

6条回答
  •  南方客
    南方客 (楼主)
    2020-12-09 18:19

    This will do the trick, but it isn't the most efficient query in the world:

    var count = query.Count();
    var pageSize = 10;
    var pageTops = query.Take(1);
    for(int i = pageSize; i < count; i += pageSize)
    {
        pageTops = pageTops.Concat(query.Skip(i - (i % pageSize)).Take(1));
    }
    return pageTops;
    

    It dynamically constructs a query to pull the (nth, 2*nth, 3*nth, etc) value from the given query. If you use this technique, you'll probably want to create a limit of maybe ten or twenty names, similar to how Google results page (1-10, and Next), in order to avoid getting an expression so large the database refuses to attempt to parse it.

    If you need better performance, you'll probably have to use a stored procedure or a view to represent your query, and include the row number as part of the stored proc results or the view's fields.

提交回复
热议问题