我有一个 List
以下类的对象:
class Entry
{
public ulong ID {get; set;}
public DateTime Time {get; set;}
}
该列表包含每个 ID 值的多个对象,每个对象具有不同的日期时间。
我可以使用 Linq 转换这个 List<Entry>
吗?到 Dictionary<ulong, DateTime>
其中键是 ID,值为 Min<DateTime>()
该 ID 的日期时间?
最佳答案
听起来您想按 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())
关于c# - 具有不同键和选定值的字典对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25244835/