C# 具有不同键和选定值的字典对象列表
我有一个C# 具有不同键和选定值的字典对象列表,c#,linq,dictionary,C#,Linq,Dictionary,我有一个列表,包含以下类别的对象: class Entry { public ulong ID {get; set;} public DateTime Time {get; set;} } 该列表包含多个每个ID值的对象,每个对象具有不同的日期时间 我可以使用Linq将此列表转换为字典,其中键是ID,值是该ID的日期时间的Min()。听起来像是要按ID分组,然后转换为字典,这样每个ID就有一个字典条目: var dictionary = entries.GroupBy(x =&
列表
,包含以下类别的对象:
class Entry
{
public ulong ID {get; set;}
public DateTime Time {get; set;}
}
该列表包含多个每个ID值的对象,每个对象具有不同的日期时间
我可以使用Linq将此
列表
转换为字典
,其中键是ID,值是该ID的日期时间的Min()
。听起来像是要按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));
或:
我想你吓跑了所有其他答案,因为我确信刚才至少有两个答案。@vipirtti:是的,有两个被删除的答案,尽管一个效率较低,另一个还不起作用。
// 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())