Jonas Stawski

Everything .NET and More

Dynamic Ordering with LINQ

I was in need to order by a sort expression passed in to a function and since I am using LINQ to SQL the only supported way to do this is by having a switch clause and construct the orderby clause based on the sort input. This could result in a huge switch statement based on the total number of possible sort expressions. I wasn't very happy with that solution until I found this example. The DynamicQuery example is the sample I needed. In that example there is a Dynamic class which extends LINQ. These extension methods allows you to pass in strings to construct the query. So I could easily do something like this:

string sortExpression = "UserName ASC";
List<User> users = DB.Users.Where(u => u.Country == "USA").OrderBy(sortExpression).ToList();

The class also extends LINQ with the use of other methods such as the Where() method. If you need this functionality in your project you can include the Dynamic class in your project and add a using (import in VB.NET) to System.LINQ.Dynamic within the class you need to use it.

I might add that this is not part of the Microsoft LINQ release and might not be supported yet. If you need to use this functionality and need to be supported read the agreement first.

Happy Programming!

Add comment