How to sort a dynamic list in C #
function void sortDynamicData(typeOfClass,SortKey)
{
List<dynamic> results = null; //results might be of any type it may contain students data or books data or professors data, hence I took as dynamic
results = services.GetMyresults(typeOfClass); //returns list of dynamic objects
results = results.OrderBy(SortKey).ToList();
...
...
...
}
My question is, I want to sort the results based on sortKey Any help would be greatly appreciated.
+3
source to share
2 answers
If possible I think it is better and easier to work with if your data is a List of T instead of a dynamic list
If you cannot change your input in the List:
public List<dynamic> Sort<T>(List<dynamic> input, string property)
{
var type = typeof(T);
var sortProperty = type.GetProperty(property);
return input.OrderBy(p => sortProperty.GetValue(p, null)).ToList();
}
Usage: you need to specify the data type in the list eg. sort Property List by Name, in which the dynamic type Person
var result = Sort<Person>(people, "Name");
================
Update:
If you cannot specify the datatype you can try this Sort ()
public List<dynamic> Sort(List<dynamic> input, string property)
{
return input.OrderBy(p => p.GetType()
.GetProperty(property)
.GetValue(p, null)).ToList();
}
Using:
var people = new List<dynamic>
{
new Person { Name = "Person 5" },
new Person { Name = "Person 2" },
new Person { Name = "Person 9" },
new Person { Name = "Person 1" }
};
var result = Sort(people, "Name");
+9
source to share