C# 如何从具有日期的对象列表中获取最小日期?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11665105/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the smallest date from a list of objects with a date?
提问by Luke
I created a simple class that represents a project:
我创建了一个代表项目的简单类:
public class EntityAuftrag
{
public string cis_auftrag { get; set; }
public string bezeich { get; set; }
public DateTime? dStart { get; set; }
public DateTime? dEnd { get; set; }
public decimal? aufstunde { get; set; }
public int id_auftrag { get; set; }
public string barcolor { get; set; }
}
Now I have a list of these. I want to extract the smallest date, how do I do that?
现在我有这些的清单。我想提取最小的日期,我该怎么做?
采纳答案by Tim Schmelter
You can use Enumerable.Min(nullvalues will be ignored unless all values are null):
您可以使用Enumerable.Min(null除非所有值都为空,否则值将被忽略):
DateTime? smallest = auftragList.Min(a => a.dStart);
Edit: if you want to find the object with the earliest(start) date, you can use OrderByand First:
编辑:如果你想找到最早(开始)日期的对象,你可以使用OrderBy和First:
EntityAuftrag auft = auftragList.OrderBy(a => a.dStart).First();
If you want the latest date, you can use Enumerable.OrderByDescendinginstead.
如果你想要最新的日期,你可以Enumerable.OrderByDescending改用。
回答by Tamir
you can use the Min() LINQ extension method:
您可以使用 Min() LINQ 扩展方法:
collection.Min(item => item.dStart);
collection.Min(item => item.dStart);
I see your date property is nullable, so if you want to avoid nulls, use the following:
我看到您的日期属性可以为空,因此如果您想避免空值,请使用以下内容:
collection.Where(item=> dStart.HasValue).Min(item => item.dStart);
collection.Where(item=> dStart.HasValue).Min(item => item.dStart);
回答by Kris Selbekk
You can do that simply with Linq. Given that you want the object with the earliest dStart, you can do the following:
你可以用 Linq 简单地做到这一点。鉴于您想要具有最早的对象dStart,您可以执行以下操作:
List<EntityAuftrag> list = someSourceOfItems;
EntityAuftrag firstObject = list.OrderBy( i => i.dStart ).First() as EntityAuftrag;
Alternatively (not sure if the above is the right syntax), you can do it this way:
或者(不确定上面的语法是否正确),您可以这样做:
List<EntityAuftrag> list = someSourceOfItems;
EntityAuftrag firstObject = (from item in list
orderby item.dStart
select item).Single() as EntityAuftrag;
Enjoy your day :-)
祝您愉快 :-)

