Let's say you have an application that has a list page that displays a collection of records (i.e. product list)- and on this list page, you want to be able to sort based on the field headers by clicking it. If clicked again, it would reverse the sort direction/order (ascending/descending) - just like Windows Explorer.In regular LINQ - this is not so easy, since LINQ is strongly typed. So let's take a look how would we do this in regular LINQ. Getting all Products by CategoryId = 5 ordering them by SupplierId
var products = from p in Products where p.CategoryId == 5 order by p.SupplierId select p;
Now if we want to order it descendingly by SupplierId I would write in LINQ:
var products = from p in Products where p.CategoryId == 5 order by p.SupplierId descending select p;So not bad. But what if we want to sort by UnitPrice?
var products = from p in Products where p.CategoryId == 5 order by p.UnitPrice select p;How about sort by ProductName?
var products = from p in Products where p.CategoryId == 5 order by p.ProductName select p;So if we want to have an option to make our product list sortable by ProductName or UnitPrice or Supplier, we would write something like this in our code:
... var products; switch (sortfield){ case "ProductName": products = from p in Products where p.CategoryId == 5 order by p.ProductName select p; break; case "UnitPrice": products = from p in Products where p.CategoryId == 5 order by p.UnitPrice select p; break; case "SupplierId": products = from p in Products where p.CategoryId == 5 order by p.SupplierId select p; break; } ...Which is OK - but what if we have 10 sortable fields? It will be a super long code and very repetitive. So how can we solve this problem with proper refactoring while still using LINQ? This is where LINQ Dynamic Library saves the day!First of all, you need to download the library:After the file is downloaded, include the Dynamic.cs (or vb) in your project. Now everytime you want to use dynamic linq, you will need to reference the namespace System.Linq.Dynamic in your code (or you can use a using statement - or Import in vb). Now using the dynamic library, the code above can be transformed into something like this:
... var products = Products .Where(p => p.CategoryId == 5) .OrderBy(sortfield); ...It is much more concise, clean, and configurable. So there you go, LINQ Dynamic Library - extremely useful!You can learn about LINQ hereScott Guthrie has an excellent post about LINQ Dynamic Library here
2 comments:
Nice and easy to follow!
Thanks, Chris!
Post a Comment