[英]Linq min date max date model querying
I'm unable to find out on how to get the min date and max date from a dictionary collection.我无法了解如何从字典集合中获取最小日期和最大日期。
My model class looks like this:我的 model class 看起来像这样:
Dictionary<string, IList<ErrorModel>> errorList
public class ErrorModel
{
public string Date { get; set; }
public int Total { get; set; }
public string Description { get; set; }
}
What I want to do get the min date and max date of the collection.我想要做的是获取集合的最小日期和最大日期。
Hope anyone can help me out希望任何人都可以帮助我
You can use Linq's Enumerable.SelectMany
to "flatten" the dictionary values, then use Min
and Max
methods:您可以使用 Linq 的
Enumerable.SelectMany
来“展平”字典值,然后使用Min
和Max
方法:
var minDate = errorList.SelectMany(s => s.Value).Min(v => v.Date);
var maxDate = errorList.SelectMany(s => s.Value).Max(v => v.Date);
However, your Date
property is defined as a string, you may not get the results you expect.但是,您的
Date
属性被定义为字符串,您可能不会得到您期望的结果。 Updating the definition to DateTime
will give the correct results using Min/Max
.将定义更新为
DateTime
将使用Min/Max
给出正确的结果。
If you instead want to get the Min/Max per dictionary Key
, you could project into an anonymous type:如果您想获取每个字典
Key
的 Min/Max,则可以投影为匿名类型:
var perKeyMinMax = errorList.Select(d => new { d.Key,
Min = d.Value.Min(v => v.Date),
Max = d.Value.Max(v => v.Date)
});
foreach (var item in perKeyMinMax)
{
Console.WriteLine($"Key: {item.Key}, Min: {item.Min}, Max: {item.Max}");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.