Wednesday, February 23, 2011

Dynamic sorting using Linq Expression

You may wonder how to avoid hard coding the sorting order in the list. Here is one of the solution using Linq Expression:

class MyClass
{
   public int age { get; set; }
   public string name { get; set; }
}

MyClass[] arr =
{
   new MyClass() {age = 10, name ="abc" },
   new MyClass() {age = 20, name ="xyz" },
   new MyClass() {age = 30, name ="cde" }
};


// create the parameter
ParameterExpression param = Expression.Parameter(typeof(MyClass), "i");

// create the property to be used base on the 
// type (ie, MyClass) in the param variable. 
// you may change the "name" to any other field.
Expression prop = Expression.Property(param, "name");

// construct the lambda expression.
Expression> lambda 
   = Expression.Lambda>(prop, param);

// compile it to a function.
Func compile = lambda.Compile();

// now, we can use the function by passing it 
// to the OrderBy() proc.
var v3 = arr.OrderBy(compile);

string s;
foreach (var item in v3)
{
   s = item.name;
}