Order matters!

27. April 2010 Uncategorized 0

As I’ve said before on this space, I’m a late adopter.  So some of my “realizations” are probably hashed out all over the web.  But I write most of this so that it burns in my memory. I’ve been working with LINQ on a new project.  I had a table come back with 55 unique records for product selection. The table contained, among other things, ProductCode, ProductDescription and linked to a table that contained a ProductSortOrder. What I wanted was a list sorted by the ProductSortOrder. The tables might look like:

  • Code         Description
  • ABC         Widget Shaft
  • ABC         Widget Flange
  • DEF         Whozit Shaft
  • DEF         Whozit joint grease
  • ZYX         Doodad ball
  • ZYX         Doodad Clips
  • Code          SortOrder
  • ZYX               1
  • ABC               2
  • DEF               3

Initially, I did something like:

return   dataContext.Products.Distinct().OrderBy(x => x.ProductSort.SortOrder).Select(x => new  productKeys 
    value = x.Code,
    description = x.Description

However, the list that this returned was sorted alphabetically, which was not the expected sort order. After some tinkering, I realized that I needed to place the OrderBy after the select, this would order my new productKeys objects in the list

return   dataContext.Products.Distinct().Select(x => new  productKeys
    Value = x.Code,
    Description = x.Description,
    Sort = x.ProductSort.SortOrder
}).OrderBy(x => x.Sort).ToList()

Now the list that is passed back takes the order: