具有不同键和选定值的字典对象列表

本文关键字:字典 对象 列表 | 更新日期: 2023-09-27 18:17:22

我有一个List的对象如下类:

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

每个ID值包含多个对象,每个对象都有不同的DateTime。

我可以使用Linq将此List<Entry>转换为Dictionary<ulong, DateTime>,其中关键是ID,值是该ID的DateTimes的Min<DateTime>()吗?

具有不同键和选定值的字典对象列表

听起来您想要按ID和分组,然后将转换为字典,这样您最终会得到每个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));

或:

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