简体   繁体   English

Linq 最小日期 最大日期 model 查询

[英]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来“展平”字典值,然后使用MinMax方法:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM