C# - 从列表中计算最小日期/最大日期
我有一个包含日期的列表:
List<string> StringDates;
[0]: "04.03.2010"
[1]: "09.03.2010"
[2]: "11.03.2010"
[3]: "12.03.2010"
[4]: "16.03.2010"
[5]: "18.03.2010"
[6]: "19.03.2010"
[7]: "23.03.2010"
[8]: "25.03.2010"
[9]: "26.03.2010"
使用 C# 从此列表中找出最小日期/最大日期的最佳/最短方法是什么?
I have a List which contains Dates :
List<string> StringDates;
[0]: "04.03.2010"
[1]: "09.03.2010"
[2]: "11.03.2010"
[3]: "12.03.2010"
[4]: "16.03.2010"
[5]: "18.03.2010"
[6]: "19.03.2010"
[7]: "23.03.2010"
[8]: "25.03.2010"
[9]: "26.03.2010"
Using C# what is the best/shortest way to find out min date / max date from this list ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
使用 ParseExact(或 TryParseExact)将它们转换为
DateTime
,然后使用 Linq 获取最小值和最大值:请注意,在您的示例中,列表已经按升序排序。如果您可以保证情况始终如此,并且您想要更好的性能,则可以只采用第一个和最后一个元素,即 O(1) 而不是 O(n)。但上面的方法更安全,因此即使您列出的列表可能始终会排序,您也可能不应该进行此优化,除非您确实需要它,以防万一有一天列表不按排序顺序排列。
Convert them to
DateTime
using ParseExact (or TryParseExact) and then use Linq to get the Min and Max:Note that in your example the list was already sorted in ascending order. If you can guarantee that this will always be the case and you want better performance, you could just take the first and last element which would be O(1) instead of O(n). But the above is safer so even if your listed probably will always be sorted, you probably shouldn't make this optimization unless you actually need it, just in case one day the list doesn't come in sorted order.
使用 linq!:
use linq!:
我喜欢简单的解决方案。
I like the simple solution.
通过 Linq,您可以执行以下操作:
Via Linq, you can do:
这与 @Jeffrey 的答案类似,但它不是解析每个日期,而是首先找到比较其字符串值的最小和最大日期,然后解析最后的值。
This is similar to @Jeffrey's answer, but instead of parsing each date, it first finds the min and max dates comparing its string values, and then it parses the values at the end.
我知道这不是对您问题的直接答案,但如果其他人来这里寻找类似的东西,可以帮助他们。
我今天在尝试从对象列表中查找最大日期时遇到了这个问题。有时,对象的日期中不会有值,因此我必须弄清楚如何在 linq 中使用 try 解析。
通过结合马克此处使用的内容,我想出了这个来解决我的问题
I know this isn't a direct answer to your question, but could help others if they come here looking for something similar.
I ran across this issue today while trying to find just the max date from a list of objects. Sometimes there won't be a value in the date for the objects so I had to figure out how to use a try parse with my linq.
From a combination of what Mark used here I came up with this to solve my problem