Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ sorting anonymous types?

Tags:

c#

linq-to-sql

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)
}
like image 684
Niels Bosma Avatar asked Jan 05 '09 19:01

Niels Bosma


2 Answers

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

like image 64
Jon Skeet Avatar answered Oct 18 '22 09:10

Jon Skeet


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)
}
like image 7
mmx Avatar answered Oct 18 '22 07:10

mmx