Reputation: 740
I have an array of Linq objects of type Link that contains values as following:
new Link {SourceId = 1, TargetId=22223}
new Link {SourceId = 1, TargetId=2221223}
new Link {SourceId = 1, TargetId=222}
new Link {SourceId = 2, TargetId=26556}
new Link {SourceId = 2, TargetId=264}
new Link {SourceId = 2, TargetId=262}
new Link {SourceId = 2, TargetId=29}
class Link
{
public int SourceId { get; set; }
public int TargetId { get; set; }
}
I need a LINQ statement to output a dictionary Dictionary<int, List<int>>
that contains following:
the distinct SourceId
as key and List of TargetId
associated with that key as the value.
Many thanks.
Upvotes: 4
Views: 137
Reputation: 2917
Dictionary<int, int> dict = links.ToDictionary(item =>
item.SourceId ,
item => item.TargetId)
Upvotes: 0
Reputation: 22555
var dic = links.GroupBy(x=>x.SourceID)
.ToDictionary(x=> x.Key, x => x.Select(y=>y.TargetId).ToList());
Upvotes: 7