2

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

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Teckniel
  • 149
  • 1
  • 1
  • 11

1 Answers1

3

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}");
}
haldo
  • 14,512
  • 5
  • 46
  • 52
  • Thanks for the reply. I will test it once i'm home. And take in your suggestion and change the date property to datetime – Teckniel Jul 12 '20 at 12:17