LINQ to SQL dynamically set order by

by Cliff 16. January 2010

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:

  1. First I specified my LINQ query and selected the results into an annonymous type and placed into a variable (var data = ...)

  2. 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.

  3. 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, ...));
    this.AddRange(selected);

I understand I could do this in fewer steps, but am leaving as it to explicitly outline the approach taken.

 

 

Cliff Gray's Info

Cliff Gray
Developer/Founder GrayTechnology.com.

E-mail me Send mail

Authors

Calendar

<<  August 2017  >>
MoTuWeThFrSaSu
31123456
78910111213
14151617181920
21222324252627
28293031123
45678910

View posts in large calendar

Blogroll

Download BlogEngine.NET

Download at CodePlex

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2017

Subscribe