简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM