简体   繁体   English

使用LINQ查找MAX / MIN列表项?

[英]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. 我有一个具有多个项目和3个道具ID,DATE,COMMENT.ID的列表。ID字段在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. 我想得到一个具有最小DATE和最新评论的ITEM.Item。 In this case 在这种情况下

1,15AUG,CommentLASTModified

Any easy way to do it using LINQ. 任何使用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. 但是,如果items集合为空,则First将引发异常。 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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