问题
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 appreciable.
回答1:
If possible, I think it's better and easier to work with if your data is List of T instead of List of dynamic
In case you cannot change your input data to 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 provide the type of data in the list, e.g. sort List by Name property in which dynamic is of Person type
var result = Sort<Person>(people, "Name");
================
Update:
In case you cannot provide the type of data, 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();
}
Usage:
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");
回答2:
var final = results.AsEnumerable().OrderBy(x => x[0])
来源:https://stackoverflow.com/questions/27683904/how-do-i-sort-the-dynamic-list-in-c-sharp