使用 属性 创建者 属性 信息并在 Lambda 中使用
Use property Created by Property Info and use in Lambda
我有一个参数为对象的方法,对象是DocumentModel
class
中属性的字符串值
private PropertyInfo SortingListView(object obj)
{
return typeof(DocumentModel).GetProperty(obj.ToString());
}
我希望 PropertyInfo
用于 lambda 表达式,如下所示:
var SortedDocuments=Documents.OrderByDescending(x => SortingListView(obj));
但它不起作用。有什么建议么?或者有什么更好的方法吗?我做得对吗?请帮忙。
如果我没看错,您正在尝试根据传递的任何 属性 对 DocumentModel
列表进行排序。你目前这样做的方式是错误的,因为你实际上是按 属性 的 PropertyInfo
对它们进行排序,并且由于所有对象都是同一类型,所以这基本上什么都不做。实际上你需要做的是这样的:
private object SortingListView<T>(T obj, string propertyName)
{
return typeof(T).GetProperty(propertyName).GetValue(obj);
}
你可以这样称呼它:
var obj = "SomePropertyName";
var sortedDocuments = Documents.OrderByDescending(x => SortingListView(x, obj));
如果你只打算在这里使用它,你也可以这样做:
var obj = "SomePropertyName";
var sortedDocuments = Documents.OrderByDescending(x =>
typeof(DocumentModel).GetProperty(obj).GetValue(x));
这样你就不需要额外的方法,你的 lambda 表达式中就有了所有的逻辑。
我有一个参数为对象的方法,对象是DocumentModel
class
private PropertyInfo SortingListView(object obj)
{
return typeof(DocumentModel).GetProperty(obj.ToString());
}
我希望 PropertyInfo
用于 lambda 表达式,如下所示:
var SortedDocuments=Documents.OrderByDescending(x => SortingListView(obj));
但它不起作用。有什么建议么?或者有什么更好的方法吗?我做得对吗?请帮忙。
如果我没看错,您正在尝试根据传递的任何 属性 对 DocumentModel
列表进行排序。你目前这样做的方式是错误的,因为你实际上是按 属性 的 PropertyInfo
对它们进行排序,并且由于所有对象都是同一类型,所以这基本上什么都不做。实际上你需要做的是这样的:
private object SortingListView<T>(T obj, string propertyName)
{
return typeof(T).GetProperty(propertyName).GetValue(obj);
}
你可以这样称呼它:
var obj = "SomePropertyName";
var sortedDocuments = Documents.OrderByDescending(x => SortingListView(x, obj));
如果你只打算在这里使用它,你也可以这样做:
var obj = "SomePropertyName";
var sortedDocuments = Documents.OrderByDescending(x =>
typeof(DocumentModel).GetProperty(obj).GetValue(x));
这样你就不需要额外的方法,你的 lambda 表达式中就有了所有的逻辑。