Often I find the need to dynamically specify the order by for a LINQ to SQL query. I came across a very nice example of this here.
I needed to use this technique with a CSLA class, so I needed to call it in a sligthly different manner than the way explained in the article. I was grouping information and needed to then dynamically set the order by and finally place the results into a CSLA read only list.
I accomplished this as follows:
- First I specified my LINQ query and selected the results into an annonymous type and placed into a variable (var data = ...)
- Next, called my OrderBy extension method on the LINQ query created in #1
var ordered = data.OrderBy(criteria.OrderByProperty, criteria.OrderByDesc);
The criteria object is the typical pattern used in CSLA to pass data to your data access methods such as fetch.
- Finally, I selected the data elements into my CSLA list item, and add to the parent list object
var selected = ordered.Select(a => MyCslaListItem.GetMyCslaListItem(a.Id, a.Name, a.Email, ...));
I understand I could do this in fewer steps, but am leaving as it to explicitly outline the approach taken.