tags:

views:

569

answers:

3

How do I do sorting when generating anonymous types in linq to sql?

Ex:

from e in linq0
order by User descending /* ??? */
select new
{
   Id = e.Id,
   CommentText = e.CommentText,
   UserId = e.UserId,
   User = (e.User.FirstName + " " + e.User.LastName).Trim()),
   Date = string.Format("{0:d}", e.Date)
}
+6  A: 

If I've understood your question correctly, you want to do this:

from e in linq0
order by (e.User.FirstName + " " + e.User.LastName).Trim()) descending 
select new
{
   Id = e.Id,
   CommentText = e.CommentText,
   UserId = e.UserId,
   User = (e.User.FirstName + " " + e.User.LastName).Trim()),
   Date = string.Format("{0:d}", e.Date)
}
Mehrdad Afshari
+1 but please use String.Format() as seeing two string concatenations next to each other hurts my eyes and I know I'm not alone.
DrJokepu
DrJokepu: It's not a problem here as it's not evaluated. It's parsed as an expression tree and sent as a SQL query to SQL Server to evaluate. In fact, it's not done twice as it is in LINQ2Objects. SQL Server will understand it and do it just once.
Mehrdad Afshari
DrJokepu
By the way, `x + " " + y` should be faster than String.Format("{0} {1}", x, y). It'll evaluate to String.Concat(x, " ", y) which will allocate the buffer only once.
Mehrdad Afshari
@Mehrdad: And also not have to parse the format string.
Jon Skeet
+6  A: 

If you're using LINQ to Objects, I'd do this:

var query = from e in linq0
            select new
            {
                Id = e.Id,
                CommentText = e.CommentText,
                UserId = e.UserId,
                User = (e.User.FirstName + " " + e.User.LastName).Trim()),
                Date = e.Date.ToString("d")
            } into anon
            order by anon.User descending
            select anon;

That way the string concatenation only has to be done once.

I don't know what that would do in LINQ to SQL though...

Jon Skeet
A: 

Would this work, as a way of avoiding Jon's select...into?

from e in linq0
let comment = new
    {
       Id = e.Id,
       CommentText = e.CommentText,
       UserId = e.UserId,
       User = (e.User.FirstName + " " + e.User.LastName).Trim()),
       Date = string.Format("{0:d}", e.Date)
    }
orderby comment.User descending
select comment
Joel Mueller