You need to implement a
Comparer[
^], and pass it to the
List.Sort[
^] method.
But since you have dynamic objects, you need to use reflection to get the values. Use
this[
^] approach:
public class DynamicSerializableComparer : IComparer<object>
{
string _property;
public DynamicSerializableComparer(string property)
{
_property = property;
}
public int Compare(object stringA, object stringB)
{
string valueA = stringA.GetType().GetProperty(_property).GetValue();
string valueB = stringB.GetType().GetProperty(_property).GetValue();
return String.Compare(valueA, valueB);
}
}
Of course, if the property you have is not string or not comparable as string, you should change the last statement accordingly.
[Update: some improvements, and a sample]
As I mentioned, you can't use
OrderBy
, since there is no property you can specify in the lambda expression.
public class DynamicSerializableComparer : IComparer<object>
{
string _property;
public DynamicSerializableComparer(string property)
{
_property = property;
}
public int Compare(object stringA, object stringB)
{
string valueA = (string)stringA.GetType().GetProperty(_property).GetValue(stringA, null);
string valueB = (string)stringB.GetType().GetProperty(_property).GetValue(stringB, null);
return String.Compare(valueA, valueB);
}
}
void Main()
{
var a1 = new { id = 1, name="Peter", email="a@x.com"};
var a2 = new { id = 2, name="John", address="USA"};
var a3 = new { id = 3, name="Robert", address="France"};
var a4 = new { id = 4, name="Albert", position="Boss"};
var a = new List<object> {a1, a2, a3, a4};
a.Sort(new DynamicSerializableComparer("name"));
a.Dump();
}
This sample will run directly in
LinqPad[
^] (I suggest you download it if you don't have it already, it is a must if you develop linq stuff...), but you can write a simple dumper or inspect the sorted list in VS. As you can see, there is not even a class defined, all objects are inline. Won't work if you change the constructor parameter to a property that's not common in all objects - in such case you have to decide and add logic to the comparer how to compare nonexistent properties. But you can use this sample to implement a comparer for your needs.