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

vip*_*tti 2 c# linq dictionary

我有List以下类的对象:

class Entry
{
    public ulong ID {get; set;}
    public DateTime Time {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

该列表包含每个ID值的多个对象,每个对象具有不同的DateTime.

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

Jon*_*eet 12

听起来你想要按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));
Run Code Online (Sandbox Code Playgroud)

要么:

                         // 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())
Run Code Online (Sandbox Code Playgroud)

  • @vipirtti:是的,有两个删除的答案,虽然一个效率较低,另一个不能正常工作. (2认同)