LINQ排序匿名类型?

时间:2009-01-05 19:54:05

标签: c# linq-to-sql

如何在linq to sql中生成匿名类型时进行排序?

例如:

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)
}

4 个答案:

答案 0 :(得分:20)

如果你正在使用LINQ to Objects,我会这样做:

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;

这样,字符串连接只需要完成一次。

我不知道在LINQ to SQL中会做些什么......

答案 1 :(得分:7)

如果我理解你的问题,你想要这样做:

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)
}

答案 2 :(得分:3)

这是否有效,作为一种避免Jon选择进入的方式?

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

答案 3 :(得分:1)

我将获得这个答案的死灵法师徽章,但我仍然认为值得展示这个片段。

var records = await (from s in db.S
  join l in db.L on s.LId equals l.Id
  where (...)
  select new { S = s, Type = l.MyType }
  ).ToListAsync();

//Data is retrieved from database by now. 
//OrderBy below is LINQ to Objects, not LINQ to SQL

if (sortbyABC)
{
  //Sort A->B->C
  records.OrderBy(sl => sl.Type, new ABC());
}
else
{
   //Sort B->A->C
   records.OrderBy(sl => sl.Type, new BAC());
}

ABC和BAC实施IComparer<MyType>