IQueryable / Linq Orderby Fail:仅对有限数量的记录进行排序

时间:2015-10-14 19:57:02

标签: c# linq sorting sql-order-by iqueryable

我有一个应用程序,一次处理数百条记录,我使用以下代码对查询进行排序,但它只对有限数量的记录进行排序和排序。

switch (sortOrder)
{
case "created":
    folders = (from f in folders orderby f.created_date ascending select f);

    //folders = folders.OrderBy(f => f.created_date.Value.Year)
    //                .ThenBy(f => f.created_date.Value.Month)
    //                .ThenBy(f => f.created_date.Value.Day);
    break;
case "created_desc":
    folders = (from f in folders orderby f.created_date descending select f);

    //folders = folders.OrderByDescending(f => f.created_date.Value.Year)
    //                    .ThenByDescending(f => f.created_date.Value.Month)
    //                    .ThenByDescending(f => f.created_date.Value.Day);
    break;
default:
    folders = folders.OrderBy(f => f.folder_number);
    break;
}

此外,当我尝试多次排序时:升序,降序然后再次升序,它不会排序超过第一个升序排序。如果这是有道理的。所以它对前20个左右的记录排序很好,但是当你继续向下滚动时,你会发现所有记录都没有正确排序。我尝试了IQueryable和Linq,两者都产生了相同的结果。

Sort by Create Date img1

Sort by Create Date img2

1 个答案:

答案 0 :(得分:1)

您在之前的Linq查询之上应用排序,因为您每次都会覆盖folders变量。相反,您应该将folders保留为未排序的数据源并单独保存已排序的结果,而不会覆盖folders

所以不要这样:

folders = (from f in folders ...

你应该这样做:

var sortedFolders = (from f in folders ...