Strongly-Typed, Dynamic Linq Order Operator
Posted by Dan Vanderboom on August 20, 2009
A Community Solution
I love social technologies like Stack Overflow, where people can collaborate loosely to share knowledge and help get things done. Stack Overflow does on a large scale what developer blogs like mine have been doing on a smaller scale: creating a community around the sharing of ideas and methods.
Every once in a while, I get some great feedback that includes a fix for one of my bugs, a performance tweak I didn’t realize was possible, or an extension to some library I left unfinished.
This morning I ran into a question about my dynamic Linq sort, solved and answered by “Ch00k”, allowing one to get compile-time checking of identifier names. Well done!
(It’s too bad Stack Overflow doesn’t promote the use of real names for professional developers to better market themselves with skill and reputation.)
My original article (with source code) is here. All I added to the library was this:
public static IOrderedEnumerable<T> Order<T>(this IEnumerable<T> Source, Expression<Func<T, object>> Selector, SortDirection SortDirection) { return Order(Source, (Selector.Body as MemberExpression).Member.Name, SortDirection); }
IEnumerable<Customer> Customers = new Customer[] { new Customer("Dan", "Vanderboom"), new Customer("Steve", "Vanderboom"), new Customer("Tracey", "Vanderboom"), new Customer("Sarah", "Barkelew") }; Customers = Customers.Order(c => c.LastName, SortDirection.Ascending); Customers = Customers.Order(c => c.FirstName, SortDirection.Descending); foreach (var cust in Customers) { Console.WriteLine(cust.FirstName + " " + cust.LastName); }
Now I can refactor these data model classes with a tool and all my dynamic sorting queries will stay in sync!
This entry was posted on August 20, 2009 at 9:02 am and is filed under Collaboration, Design Patterns, Dynamic Programming, Language Extensions, LINQ, Object Oriented Design, Open Source, Social Networking. Tagged: Collaboration, dynamic query, LINQ, social networks. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
Bryan Watts said
I like the idea. I would suggest a little more defense against incorrect expressions, though. With public code, you can’t guarantee everyone will pass a MemberExpression to you; if they don’t, the code as written will fail with a NullReferenceException rather than a meaningful error.
Better Tool Support for .NET « Critical Development said
[…] of lambda expressions to select identifiers instead of using evil “magical strings”. From my article on dynamically sorting Linq queries, the use of “magic strings” would force me to write something like this to dynamically sort a […]
Joe Hammer said
Excellent.
Thank you.