LINQ GroupBy以给定对象作为值返回字典

时间:2017-09-05 13:43:45

标签: c# linq

我有一个IEnumerable<ValueObj>对象,其中包含多个有效的ValueObj个对象。我想按ID对这些对象进行分组,并从Dictionary<Guid, IEnumerable<ValueObj>>接收密钥为Id的ValueObj,而值不变ValueObj

public class ValueObj
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public DateTime Time { get; set; }
    public double Result { get; set; }
}

我试图弄乱Linq GroupBy,但没有成功

IEnumerable<ValueObj> persons = ...;
var results = persons.GroupBy(
    p => p.Id, 
    p => p,
    (key, g) => new { PersonId = key, Cars = g.ToList() });

1 个答案:

答案 0 :(得分:4)

试试这个:

IEnumerable<ValueObj> col = ...;
var dict = col.GroupBy(x => x.Id).ToDictionary(x => x.Key, x => x.ToList());