Reputation: 282
So I have a
IEnumerable<Dictionary<string,string>>
gotten from using
var differences = activeCalls.Where(l1 => !tempActiveCalls.Any(l2 => l1 == l2));
that holds an id as the key and a date formatted as
DateTime.ToString("s")
What I would like is to get the key value pair that has the earliest date. Right now I am using
List<Dictionary<string, DateTime>> minDate = new List<Dictionary<string, DateTime>>();
//convert strings to dates
foreach(var dictionary in differences)
{
foreach(var kvp in dictionary)
{
minDate.Add(new Dictionary<string, DateTime>()
{
{kvp.Key, DateTime.ParseExact(kvp.Value,"yyyy'-'MM'-'dd'T'HH':'mm':'ss",null) }
});
}
}
to convert the strings into datetime format but am stuck on how to select the minimum key/value pair based on date. I also don't think this is the simplest method at all. Any help is appreciated.
Upvotes: 2
Views: 898
Reputation: 62213
Here is one way to do it, order it by key and get the first element. This works because of the way the key is structured in your dictionary instances, DateTime.ToString("s")
produces a sortable date time string (its ISO notation), there is no need to convert it to a DateTime
type. The SelectMany
will flatten the dictionary instances into a single collection. Using OrderBy
will order ascending (earliest to latest).
var result = differences.SelectMany(y => y).OrderBy(x => x.Key).First();
You will need to include using System.Linq;
at the top of your code file.
Upvotes: 2