我有一种方法可以将一些动态排序应用于IQueryable。以下是相关代码:
if (orderBy != 0)
{
if (thenBy != 0 && thenBy != orderBy)
{
results = results.OrderBy(request.OrderBy + " ASC, " + request.ThenBy + " ASC");
}
else if (thenByDesc != 0 && thenByDesc != orderBy)
{
results = results.OrderBy(request.OrderBy + " ASC, " + request.ThenByDesc + " DESC");
}
else
{
results = results.OrderBy(request.OrderBy + " ASC");
}
}
问题是订购似乎没有正常工作。例如,按财产排序"名称"这只是一个字符串,似乎无法工作。
我在确定排序之前找到了toList()
结果的修复,如下所示:
orderedResults = results.ToList().AsQueryable();
然后在orderedResults
变量上执行OrderBy。这样会很好,但我订购的结果可能包含1000个项目。在这种情况下的表现非常糟糕。是否有其他解决方案没有将集合带入内存?
更新
事后看来,我发布的代码并不清楚。这是整个方法:
public static IOrderedQueryable<TSource> Order<TSource, TOrdering>(this IQueryable<TSource> results, RequestBase<TOrdering> request)
{
var genericType = typeof(TOrdering);
if (!genericType.IsEnum) return (IOrderedQueryable<TSource>)results;
var orderBy = Convert.ToInt32(request.OrderBy as Enum);
var orderByDesc = Convert.ToInt32(request.OrderByDesc as Enum);
var thenBy = Convert.ToInt32(request.ThenBy as Enum);
var thenByDesc = Convert.ToInt32(request.ThenByDesc as Enum);
if (orderBy != 0)
{
if (thenBy != 0 && thenBy != orderBy)
{
results = results.OrderBy(request.OrderBy + " ASC, " + request.ThenBy + " ASC");
}
else if (thenByDesc != 0 && thenByDesc != orderBy)
{
results = results.OrderBy(request.OrderBy + " ASC, " + request.ThenByDesc + " DESC");
}
else
{
results = results.OrderBy(request.OrderBy + " ASC");
}
}
else if (orderByDesc != 0)
{
if (thenBy != 0 && thenBy != orderByDesc)
{
results = results.OrderBy(request.OrderByDesc + " DESC, " + request.ThenBy + " ASC");
}
else if (thenByDesc != 0 && thenByDesc != orderByDesc)
{
results = results.OrderBy(request.OrderByDesc + " DESC, " + request.ThenByDesc + " DESC");
}
else
{
results = results.OrderBy(request.OrderByDesc + " DESC");
}
}
return (IOrderedQueryable<TSource>)results;
}
request.OrderBy
和其他排序属性是枚举。此枚举可以包含诸如&#39; Name&#39;,&#39; SubmittedDate&#39;等值,以便在其上订购results
。这就是我调用方法的方法:
reportsResponses = reportsResponses.Order(request);
更新2
有关代码的更多信息。我提到如果我在应用任何订购之前首先执行此操作,则排序有效:
results = results.ToList().AsQueryable();
在此之前,结果是从mongo驱动程序计算的。我们通过查询mongodb获得结果。 mongo在这里是薄弱环节吗?