gpt4 book ai didi

c# - 如何编写 Linq 表达式以在一组实体上调用 OrderBy?

转载 作者:行者123 更新时间:2023-11-30 13:23:25 25 4
gpt4 key购买 nike

有人可以解释构建表达式的语法吗?

这篇 MSDN 文章大有帮助,但它处理的是一个简单的字符串列表,我的数据集包含我自己的自定义对象。

http://msdn.microsoft.com/en-us/library/bb882637.aspx

最佳答案

先写代码,再解释。

IQueryable<T> data = this.Database.ObjectsOfType<T>();

var eachItem = Expression.Parameter(typeof(T), "item");
var propertyToOrderByExpression = Expression.Property(eachItem, propertyName);

var runMe = Expression.Call(
typeof(Queryable),
"OrderBy",
new Type[] { data.ElementType, typeof(IComparable) },
data.Expression,
Expression.Lambda<Func<T,IComparable>>(propertyToOrderByExpression, new ParameterExpression[] { eachItem }));

因此,首先我们将数据作为可查询对象获取。这有一种“根”表达式属性,我们需要它。

eachItem 是一个表达式,表示 Lambda 中的参数占位符,如果您愿意的话,可以转到中的符号。

然后我们创建一个表达式,对用户在 propertyName 中指定的属性名称执行读取操作。

我们最终构建了一个表达式,该表达式调用可查询数据上的 OrderBy 方法。我们说(按论证顺序):

Expression.Call(
[what's the type on which we want to call a method?],
[what's the name of the method we're calling?],
[if this method is generic, what are the types it deals with?],
{
[expression representing the data],
[expression for the lambda using the reader exp + each item exp]
})

最后两个在 { } 中,因为它实际上是一个参数数组。我使用了 IComparable,因为该属性可以是任何类型,但显然需要具有可比性才能被排序。

卢克

关于c# - 如何编写 Linq 表达式以在一组实体上调用 OrderBy?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12219404/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com