简体   繁体   中英

Find MAX/MIN list item using LINQ?

I have a list Having multiple Items and 3 props ID,DATE,COMMENT.ID field is Auto incremented in DATABASE.

Let say list Contains

2,16AUG,CommentMODIFIED
1,15AUG,CommentFIRST
3,18AUG,CommentLASTModified

I want to get a single ITEM.Item Having Minimum DATE and having Latest Comment. In this case

1,15AUG,CommentLASTModified

Any easy way to do it using LINQ.

orderedItems = items.OrderBy(x => x.Date);

var result = items.First();
result.Comment = items.Last().Comment;

To get a single item out of the list, you can order the items then take the first one, like this:

var result = items
    .OrderByDescending(x => x.Date)
    .First();

But First will throw an exception if the items collection is empty. This is a bit safer:

var result = items
    .OrderByDescending(x => x.Date)
    .FirstOrDefault();

To get the min / max of different columns you can do this:

var result = 
    new Item {
         Id = 1,
         Date = items.Min(x => x.Date),
         Comment = items.Max(x => x.Comment)
    };

But this will require two trips to the database. This might be a bit more efficient:

var result = 
    (from x in items
     group x by 1 into g
     select new Item {
         Id = 1,
         Date = g.Min(g => g.Date),
         Comment = g.Max(g => g.Comment)
     })
    .First();

Or in fluent syntax:

var result = items
    .GroupBy(x => 1)
    .Select(g => new Item {
         Id = 1,
         Date = g.Min(g => g.Date),
         Comment = g.Max(g => g.Comment)
     })
    .First();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM