从日期列表中查找最小日期值

时间:2019-01-28 17:47:13

标签: c# linq linq-to-objects

这将为我提供我的开始日期列表:(它们存储为 STRING

var startDate = myValues.Select(t => t.StartDate).ToList();

我只需要它从中选择最早的日期值即可。如果这是一个空字符串,那么它也是获胜者;如果没有空字符串,那么只需看看哪个最早。

有没有办法我可以将LINQ combine 与上面的部分一起使用,以便一次性找到它?而不是单独编写更多逻辑以从该列表中查找最小日期?

2 个答案:

答案 0 :(得分:2)

类似的东西:

string winner = myValues.Select(t => t.StartDate)
    .Select(s => new{ str = s, date = DateTime.TryParse(s, out DateTime dt) ? dt : new DateTime?() })
    .OrderByDescending(x => String.IsNullOrEmpty(x.str))
    .ThenByDescending(x => x.date.HasValue)
    .ThenBy(x => x.date.GetValueOrDefault())
    .Select(x => x.str)
    .First();

答案 1 :(得分:0)

这可能对您有帮助

var result = myValues?.Where(t=>!string.IsNullOrEmpty(t.StartDate))?.
  Select(t => { DateTime.TryParse(t.StartDate, out DateTime date); return date;})?.
  Min();