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#的是找出最小日期/最大日从该列表中的最佳/最短路径?
解决方案
我喜欢简单的解决方案。
DateTime minDate = DateTime.MaxValue;
DateTime maxDate = DateTime.MinValue;
foreach (string dateString in StringDates)
{
DateTime date = DateTime.Parse(dateString);
if (date < minDate)
minDate = date;
if (date > maxDate)
maxDate = date;
}
其他提示
转换他们使用ParseExact(或TryParseExact)至DateTime
,然后使用LINQ到获得最小和最大:
List<DateTime> dates = StringDates
.Select(x => DateTime.ParseExact(x, "dd.MM.yyyy", null))
.ToList();
DateTime minDate = dates.Min();
DateTime maxDate = dates.Max();
请注意,在你的榜样名单已经升序排列。如果你能保证,这将永远是这样,你想更好的性能,你可以只取这将是O(1)而不是O(n)的第一个和最后一个元素。但上面的是安全所以即使你的上市可能会一直进行排序,你可能不应该,除非你真的需要它,以防万一有一天列表不进来有序使这种优化。
使用LINQ:
var list = new List<DateTime>();
list.Add(new DateTime(2010, 1, 1));
list.Add(new DateTime(2008, 1, 1));
list.Add(new DateTime(2009, 1, 1));
Console.WriteLine(list.Max(date => date));
Console.WriteLine(list.Min(date => date));
通过LINQ的,你可以这样做:
from row in StringDates
group row by true into r
select new {
min = r.Min(z => z),
max = r.Max(z => z)
}
这是类似于但@杰弗里的答案,而不是分析每个日期,它首先找到分钟,并将它的字符串值最大的日期,然后将其在端部解析值。
// This method handles the date comparisons
private int WeirdComparer(string strDate1, string strDate2)
{
int res = string.Compare(strDate1, 6, strDate2, 6, 4);
if (res == 0)
res = string.Compare(strDate1, 3, strDate2, 3, 2);
if (res == 0)
res = string.Compare(strDate1, 0, strDate2, 0, 2);
return res;
}
public void FindMinAndMaxDates(IList<string> strDates, out DateTime minDate, out DateTime maxDate)
{
string min = "99.99.9999";
string max = "00.00.0000";
foreach (string strDate in strDates)
{
if (WeirdComparer(strDate, min) < 0)
min = strDate;
if (WeirdComparer(strDate, max) > 0)
max = strDate;
}
minDate = DateTime.ParseExact(min, "dd.MM.yyyy", null);
maxDate = DateTime.ParseExact(max, "dd.MM.yyyy", null);
}
我知道这是不是直接回答你的问题,但可以帮助其他人,如果他们来这里寻找类似的东西。
我碰到这个问题,今天跑了,而试图找到刚刚从对象列表的最大日期。有时,不会有在日期为对象的值,所以我必须弄清楚如何使用try解析与我的LINQ。
从我想出了这个解决我的问题。
什么马克这里使用组合 List<string> stringDates = new List<string>();
stringDates.Add("Not a date");
stringDates.Add("2015-01-01");
stringDates.Add("2015-10-10");
stringDates.Add("2015-9-10");
stringDates.Add("123");
DateTime sapInvoiceDate;
DateTime tempDate = DateTime.MinValue;
sapInvoiceDate = stringDates.Select(x => DateTime.TryParse(x, out tempDate)).Select(x => tempDate).Max();
不隶属于 StackOverflow