erexo
erexo

Reputation: 533

LINQ GroupBy return dictionary with given objects as value

I have an IEnumerable<ValueObj> object with multiple valid ValueObj objects in it. I would like to group those objects by Id and receive Dictionary<Guid, IEnumerable<ValueObj>> where the Key is Id from ValueObj, and Value is just unchanged ValueObj.

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

I've tried to mess with Linq GroupBy but with no success

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

Upvotes: 0

Views: 446

Answers (1)

Ricardo Peres
Ricardo Peres

Reputation: 14555

Try this:

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

Upvotes: 4

Related Questions