Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of objects to Dictionary with distinct keys and selected values

I have a List of objects of following class:

class Entry
{
    public ulong ID {get; set;}
    public DateTime Time {get; set;}
}

The list contains several object per ID value, each with different DateTime.

Can I use Linq to convert this List<Entry> to a Dictionary<ulong, DateTime> where the key is the ID and the value is Min<DateTime>() of the DateTimes of that ID?

like image 476
vipirtti Avatar asked Nov 06 '25 21:11

vipirtti


1 Answers

Sounds like you want to group by ID and then convert to a dictionary, so that you end up with one dictionary entry per ID:

var dictionary = entries.GroupBy(x => x.ID)
                        .ToDictionary(g => g.Key,
                                      // Find the earliest time for each group
                                      g => g.Min(x => x.Time));

Or:

                         // Group by ID, with each value being the time
var dictionary = entries.GroupBy(x => x.ID, x => x.Time)
                         // Find the earliest value in each group
                        .ToDictionary(g => g.Key, g => g.Min())
like image 93
Jon Skeet Avatar answered Nov 08 '25 12:11

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!