Abin
Abin

Reputation: 2956

Use property Created by Property Info and use in Lambda

I have a method with parameter as object, the object is a string value of properties in DocumentModel class

 private PropertyInfo SortingListView(object obj)
 {
     return typeof(DocumentModel).GetProperty(obj.ToString());
 }

I want the PropertyInfo to be used in a lambda expression like below:

 var SortedDocuments=Documents.OrderByDescending(x => SortingListView(obj));

But it's not working. Any suggestions? Or any better way? Am I doing it correctly? Please help.

Upvotes: 0

Views: 37

Answers (1)

msmolcic
msmolcic

Reputation: 6557

If I got it right, you're trying to sort your list of DocumentModel by whatever property is passed. The way you're currently doing it is wrong because you're actually sorting them by PropertyInfo of your property and since all objects are of the same type this basically does nothing. What you need to do actually is something like this:

private object SortingListView<T>(T obj, string propertyName)
{
    return typeof(T).GetProperty(propertyName).GetValue(obj);
}

You can call it this way:

var obj = "SomePropertyName";
var sortedDocuments = Documents.OrderByDescending(x => SortingListView(x, obj));

If you're only going to use it here, you could also do it like this:

var obj = "SomePropertyName";
var sortedDocuments = Documents.OrderByDescending(x =>
                          typeof(DocumentModel).GetProperty(obj).GetValue(x));

This way you don't need extra method, you have all the logic inside your lambda expression.

Upvotes: 1

Related Questions