Search code examples
c#linq

How do I specify the Linq OrderBy argument dynamically?


How do I specify the argument passed to orderby using a value I take as a parameter?

Ex:

List<Student> existingStudends = new List<Student>{ new Student {...}, new Student {...}}

Currently implementation:

List<Student> orderbyAddress = existingStudends.OrderBy(c => c.Address).ToList();

Instead of c.Address, how can I take that as a parameter?

Example

 string param = "City";
 List<Student> orderbyAddress = existingStudends.OrderByDescending(c => param).ToList();

Solution

  • Here's a possiblity using reflection...

    var param = "Address";    
    var propertyInfo = typeof(Student).GetProperty(param);    
    var orderByAddress = items.OrderBy(x => propertyInfo.GetValue(x, null));