1

Possible Duplicate:
Dynamic LINQ OrderBy

How can I pass a value to an OrderBy or OrderByDescending statement in Linq? I am trying to get the property name dynamically:

x.GetType().GetProperty(sortField)

Which doesnt seem to work. Any Ideas?

private void DynamicSort(ref List<Quote> myQuotes, String sortField, String direction)
{         
        if(direction == "ASC"){
            this.grdViewDrafts.DataSource = myQuotes.OrderBy(x =>  x.GetType().GetProperty(sortField)).ToList();
        }else{
            this.grdViewDrafts.DataSource = myQuotes.OrderByDescending(x => x.GetType().GetProperty(sortField)).ToList();
        }

}

Solution:

this.grdViewDrafts.DataSource =  myQuotes.OrderBy(x => x.GetType().GetProperty(sortField).GetValue(x, null)).ToList(); 
Community
  • 1
  • 1
PhillyNJ
  • 3,559
  • 4
  • 33
  • 57

1 Answers1

4

The actual problem in your code is that you just get PropertyInfo object but not the property value itself. To get property value you have to call GetValue() method of the PropertyInfo object.

JSK NS
  • 3,076
  • 2
  • 21
  • 40
Anton Sorokin
  • 391
  • 1
  • 6
  • 10