vipirtti
vipirtti

Reputation: 1078

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?

Upvotes: 4

Views: 4719

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500535

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())

Upvotes: 14

Related Questions