How to give Property Name in linq orderBy based on string Property name in C#

2.1k views Asked by At

I am doing sorting functionality based on columns name. have 24 columns while descending I am doing the switch condition based on direction doing the descending.

so I have specified switch condition based on descending for ascending only one default condition based on the incoming column name.i don't want the condition for ascending as well. Here i am trying to get the property name and pass in order by default but it is not working.

anyone provide a better solution

public Static List<Students> Sort( string columnname , bool direction, List<Student> students){

Switch(columnname){
case "Name" when direction= false;
 students.OrderByDescending(n=> n.Name)).ToListAsync();
 break;

case "Marks" when direction= false;
 students.OrderByDescending(n=> n.Marks).ToListAsync();
 break;

etc 25 columns

default:         // trying to pass a column name dynamically but the order is not working

var getPropertyName = nameof(columnname);
students.OrderBy(n=> getPropertyName).ToListAsync();  // 

tried with the incoming property name.

// Used reflection 
   var  convertProperty = typeof(Student).GetProperty(columnname);
  students.OrderByDescending(n=> convertProperty)).ToListAsync();  

// but order is not working what ever order we have that executed

if try with a specific column name it is working
students.OrderBy(n=> n.Subjects)).ToListAsync();
students.OrderBy(n=> n.Marks)).ToListAsync();
}
return students

}
2

There are 2 answers

2
Jan1902 On BEST ANSWER

The second last of your examples is actually quite close to something that should work.

Ignoring everything around it the following should be a working version of the mentioned example:

// Used reflection 
var convertProperty = typeof(Student).GetProperty(columnname);
students.OrderByDescending(n => convertProperty.GetValue(n).ToString() ?? string.Empty).ToListAsync();

To be fair, I haven't tried out this code, so I might have made a mistake somewhere, given this is typed freely without an IDE, but it should give a general Idea, right?

Edit

If you are using C# 6.0 and upwards you can use null checking like mentioned above, otherwise you can also use the following

students.OrderByDescending(n => (convertProperty.GetValue(n) ?? string.Empty).ToString()).ToListAsync();
1
Meysam Asadi On

You can easily use this code:

students = students.OrderByDescending(x => x.GetType().GetProperty(columnname).GetValue(x, null)).ToList();