Linq min date max date model querying

Viewed 233

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

1 Answers

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