LINQ sorting anonymous types?

前端 未结 4 1804
小鲜肉
小鲜肉 2021-02-06 07:17

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,
            


        
相关标签:
4条回答
  • 2021-02-06 07:20

    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
    
    0 讨论(0)
  • 2021-02-06 07:21

    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)
    }
    
    0 讨论(0)
  • 2021-02-06 07:26

    I'm going to get a necromancer badge for this answer, but I still think it's worth showing this snippet.

    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 and BAC implement IComparer<MyType>.

    0 讨论(0)
  • 2021-02-06 07:29

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

    0 讨论(0)
提交回复
热议问题