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:

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

Add Comment
1 Answer(s)

You can use Linq’s Enumerable.SelectMany to "flatten" the dictionary values, then use Min and Max methods:

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. Updating the definition to DateTime will give the correct results using Min/Max.


If you instead want to get the Min/Max per dictionary Key, you could project into an anonymous type:

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}"); } 
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.