Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 对列表排序<;T>;通过对象的未知属性_C#_Asp.net Core_Entity Framework Core - Fatal编程技术网

C# 对列表排序<;T>;通过对象的未知属性

C# 对列表排序<;T>;通过对象的未知属性,c#,asp.net-core,entity-framework-core,C#,Asp.net Core,Entity Framework Core,我有一个网站,它使用很多方法从我的数据上下文中获取列表。我最近开始将这些方法改为通用方法,以减少代码量;但是,许多方法都要求我在返回列表之前执行OrderBy。这就是我已经在使用的泛型方法 public List<TEntity> GetObjects<TEntity>() where TEntity : class { return this.dataContext.Set<TEntity>().ToList(); } public Lis

我有一个网站,它使用很多方法从我的数据上下文中获取列表。我最近开始将这些方法改为通用方法,以减少代码量;但是,许多方法都要求我在返回列表之前执行OrderBy。这就是我已经在使用的泛型方法

public List<TEntity> GetObjects<TEntity>()
    where TEntity : class
{
    return this.dataContext.Set<TEntity>().ToList();
}
public List GetObjects()
地点:班级
{
返回此.dataContext.Set().ToList();
}
如果可能的话,我希望有类似的东西,我可以传入我希望列表按其排序的变量的名称,并在泛型方法返回它之前使用它对列表进行排序。也许是这样的:

public List<TEntity> GetObjects<TEntity>(string orderedVariable)
    where TEntity : class
{
    // Code to get information about the property of the class
    return this.dataContext.Set<TEntity>()OrderBy(// Code to sort the list).ToList();
}
公共列表GetObjects(字符串orderedVariable)
地点:班级
{
//获取有关类属性的信息的代码
返回此.dataContext.Set()OrderBy(//对列表进行排序的代码);
}

尝试使用nuget package System.Linq.Dynamic.Core(),只需将字符串传递给orderBy方法即可。 例如,它在我们的泛型方法中的外观

query.OrderBy(input.Sorting??“id asc”)


它接受来自通用输入的字符串,如果为空,则默认情况下我们使用Id列进行排序。

这取决于通用性如何。您可以执行如下操作:
GetObjects(Func orderClause)
然后
.Set().Orderby(orderClause.ToList()沿着这些线的东西。但是如果你只想传递字符串,你可以做一些反射的把戏来计算属性。尽管如此,我从来没有看到过这样的结果。这里有可能回答吗?如果可以的话,我一定会试试的。现在,dotnet甚至不允许我在不崩溃的情况下使用--help命令,所以我必须等待修复。调用方知道他们想要哪个属性吗?还是需要最终用户来选择?是否要按所属类型的属性排序?@Will该解决方案是LinqToObject解决方案。我怀疑OP想要一个LinqToEF解决方案。这非常有效!非常感谢。