【问题标题】:List of objects to Dictionary with distinct keys and selected values具有不同键和选定值的字典对象列表
【发布时间】:2014-08-11 13:47:48
【问题描述】:

我有一个 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>()

【问题讨论】:

    标签: c# linq dictionary


    【解决方案1】:

    听起来您想按 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())
    

    【讨论】:

    • 我认为你吓跑了所有其他答案,因为我确信刚才至少有两个答案。
    • @vipirtti:是的,有两个已删除的答案,虽然一个效率较低,另一个还不能工作。
    猜你喜欢
    • 2019-08-18
    • 1970-01-01
    • 1970-01-01
    • 2019-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-17
    相关资源
    最近更新 更多