How to select only the records with the highest date in LINQ

前端 未结 5 1046
一向
一向 2020-11-28 03:15

I have a table, \'lasttraces\', with the following fields.

Id, AccountId, Version, DownloadNo, Date

The data looks like this:



        
相关标签:
5条回答
  • 2020-11-28 03:44

    If you just want the last date for each account, you'd use this:

    var q = from n in table
            group n by n.AccountId into g
            select new {AccountId = g.Key, Date = g.Max(t=>t.Date)};
    

    If you want the whole record:

    var q = from n in table
            group n by n.AccountId into g
            select g.OrderByDescending(t=>t.Date).FirstOrDefault();
    
    0 讨论(0)
  • 2020-11-28 03:46

    If you want the whole record,here is a lambda way:

    var q = _context
                 .lasttraces
                 .GroupBy(s => s.AccountId)
                 .Select(s => s.OrderByDescending(x => x.Date).FirstOrDefault());
    
    0 讨论(0)
  • 2020-11-28 03:48

    Go a simple way to do this :-

    Created one class to hold following information

    • Level (number)
    • Url (Url of the site)

    Go the list of sites stored on a ArrayList object. And executed following query to sort it in descending order by Level.

    var query = from MyClass object in objCollection 
        orderby object.Level descending 
        select object
    

    Once I got the collection sorted in descending order, I wrote following code to get the Object that comes as top row

    MyClass topObject = query.FirstRow<MyClass>()
    

    This worked like charm.

    0 讨论(0)
  • 2020-11-28 03:55

    It could be something like:

    var qry = from t in db.Lasttraces
              group t by t.AccountId into g
              orderby t.Date
              select new { g.AccountId, Date = g.Max(e => e.Date) };
    
    0 讨论(0)
  • 2020-11-28 03:59

    Here is a simple way to do it

    var lastPlayerControlCommand = this.ObjectContext.PlayerControlCommands
                                    .Where(c => c.PlayerID == player.ID)
                                    .OrderByDescending(t=>t.CreationTime)
                                    .FirstOrDefault();
    

    Also have a look this great LINQ place - LINQ to SQL Samples

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