这段代码到底是做什么的? (C#)
我一直在读一本C# 的书。我是一名 VB.NET 开发人员(而且是一名非常初级的开发人员),并且我在使用以下包含许多我以前从未见过的内容的代码时遇到了很多麻烦。我确实有 Lambda 表达式的基本知识。
public List<T> SortByPropertyName(string propertyName, bool ascending)
{
var param = Expression.Parameter(typeof(T), "N");
var sortExpression = Expression.Lambda<Func<T, object>>
(Expression.Convert(Expression.Property(param, propertyName),
typeof(object)), param);
if (ascending)
{
return this.AsQueryable<T>().OrderBy<T, object>(sortExpression).ToList<T>();
}
else
{
return this.AsQueryable<T>().OrderByDescending<T, object>(sortExpression).ToList<T>
}
}
有人能告诉我这段代码在做什么以及使用了哪些概念吗? 我还尝试将此代码转换为 VB.NET,但运气不佳,因此任何帮助也将不胜感激。
I've been reading a book which is in C#. I'm a VB.NET developer (and a very junior one at that) and I'm having a lot of trouble with the following code that contains lots of things I've never seen before. I do have a basic knowledge of Lambda Expressions.
public List<T> SortByPropertyName(string propertyName, bool ascending)
{
var param = Expression.Parameter(typeof(T), "N");
var sortExpression = Expression.Lambda<Func<T, object>>
(Expression.Convert(Expression.Property(param, propertyName),
typeof(object)), param);
if (ascending)
{
return this.AsQueryable<T>().OrderBy<T, object>(sortExpression).ToList<T>();
}
else
{
return this.AsQueryable<T>().OrderByDescending<T, object>(sortExpression).ToList<T>
}
}
Could anybody illuminate me as to what this code is doing and what concepts are being used?
I am also trying to convert this code into VB.NET with little luck so any help there would be appreciated as well.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
总的来说,代码按指定的属性名称以升序或降序对某些内容(大概是列表?)进行排序。必须已经在此类中的其他位置指定了泛型类型
T
。该代码通过调用
Expression.Parameter
创建一个新的ParameterExpression
,然后将该参数传递到Expression.Lambda
函数,该函数创建一个新的 lambda 表达式。然后,该表达式用于通过调用
OrderBy
或OrderByDescending
函数(选择取决于ascending
参数)对列表进行排序,并返回排序后的结果列表作为新的List
。我现在不在 Visual Studio 前面,但这对您来说应该是一个足够接近 VB 的翻译。
Overall, the code is sorting something (presumably a list?) by the specified property name in either ascending or descending order. There must already be a generic type
T
specified somewhere else in this class.The code creates a new
ParameterExpression
by callingExpression.Parameter
, then passes that parameter into theExpression.Lambda
function, which creates a new lambda expression.This expression is then used to sort the list by calling the
OrderBy
orOrderByDescending
function (the choice depending on theascending
parameter) and returns the sorted list as a newList<T>
.I'm not in front of Visual Studio at the moment, but this should be a sufficiently close translation to VB for you.
这应该有效:
另请参阅: http://www.codeproject.com/KB/recipes /Generic_Sorting.aspx
This should work:
See also: http://www.codeproject.com/KB/recipes/Generic_Sorting.aspx