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.
Note: If you want to change the sorting of an instance of the DynamicComparer, you can call the “Initialize” method on the instance and pass in a new ORDER BY string or a SortProperty array. At the next step, we call the “ Sort ” method on the “persons” list passing in a reference to the comparer.Compare method.
This article will show you a tricky way to sort dynamic data in Excel, and keep the sorting update automatically when the original data changes at once. Sort synamic data in Excel with formula Sort synamic data in Excel with formula 1. Insert a new column at the beginning of the original data.
How to sort a list in C# | List.Sort () Method Set -1. List<T>.Sort () Method is used to sort the elements or a portion of the elements in the List<T> using either the specified or default IComparer<T> implementation or a provided Comparison<T> delegate to compare list elements. There are total 4 methods in the overload list ...
The logic we use to sort the array elements in ascending order is as follows − for (i = 0; i < n; ++i) { for (j = i + 1; j < n; ++j) { if (num[i] > num[j]) { a = num[i]; num[i] = num[j]; num[j] = a; } } }
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");
var final = results.AsEnumerable().OrderBy(x => x[0])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With