chris carter's web log

Home |  Contact |  Admin
 

Dynamic.cs: Yummy Linq Goodness

Posted on August 20, 2008

While testing out some more asp.net mvc stuff, I came up with a need to order a list of objects by property name(a string value).  Assuming I have a list of customers named customerList, i want to do something like: customerList.OrderBy("FirstName"), and get back a list of customers sorted by the FirstName property of each customer instance in the list.

Originally, I used something based on this post.  It looked like this:

public IEnumerable<TModel> OrderBy(string propertyName, bool sortAscending){

  if (String.IsNullOrEmpty(propertyName))
    throw new ArgumentNullException("propertyName");

  PropertyInfo property = typeof(TModel).GetProperty(propertyName);
  if (property == null)
    throw new NullReferenceException(
      String.Format("property '{0}' was not found on type '{1}'",
      propertyName,
      typeof(TModel).Name));

  if (sortAscending)
    return _models.OfType<TModel>().OrderBy(mo => property.GetValue(mo, null));
  else
    return _models.OfType<TModel>().OrderByDescending(mo => property.GetValue(mo, null));
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

But then I found dynamic.cs located in the DynamicQuery project in the CSharpSamples.zip file.  Wicked cool shizzle. Now that method above looks like this:

public IEnumerable<TModel> OrderBy(string propertyName, Sort sortDirection){

  if (String.IsNullOrEmpty(propertyName))
    throw new ArgumentNullException("propertyName");

  return _models.AsQueryable<TModel>()
    .OrderBy(propertyName, sortDirection.ToString());
}
1
2
3
4
5
6
7
8

Now using my updated code looks like this:

IEnumerable<Customer> customers = customerRepository.OrderBy("FirstName", Sort.Descending);
1

I had to dig a little for this, but the signature on OrderBy, one of them anyway, looks like this:

IQueryable<T> OrderBy<T>(string ordering, params object[] values)
1

To use this, pass in the property name in the first spot, and "Ascending" or "Descending" in the second spot, like this:

customerList.AsQueryable<Customer>().OrderBy("FirstName", "Descending")
1

I felt like sticking the OrderBy method on my IRepository interface which, using your favorite subversion tool, can be checked out here:
http://svn.chrisjcarter.com/public/EPS

There's some really cool geeky code in dynamic.cs, check it out.

Comments

Alper

For the rest of us still working in 2.0 world. I created this dynamic sort method which uses reflection to sort a list.

http://codekeep.net/snippets/ef0338bd-bd9a-4b46-a58d-ae67fd386da9.aspx

Chris

See, I would have used something that too if it had popped up in the first couple of hundred google results, I wasn't really looking for anything elaborate.  Nice bit of code though, thanks for the link.

Post a Comment

(required)
(required)
(no HTML!)