首页 > 解决方案 > 使用反射 linq c# 进行排序

问题描述

我正在尝试使用反射对我的记录进行排序

IQueryable<Container> containers = this.Repository.Containers;
foreach (var prop in typeof(Container).GetProperties())
{
    if (sortField.IndexOf(prop.Name, StringComparison.OrdinalIgnoreCase) >= 0)
    {
        containers = sortDir == "desc"
            ? containers.OrderByDescending(x => prop.GetValue(x, null))
            : containers.OrderBy(x => prop.GetValue(x, null));
    }
}
var total = await containers.CountAsync();
... Skip/Take actions ...

但执行此行后出现错误var total = await containers.CountAsync();

The LINQ expression '(c) => (Unhandled parameter: __prop_2).GetValue(
    obj: c.Outer, 
    index: null)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

我的代码有什么问题?

标签: c#linq

解决方案


推荐阅读