Mike Gleason jr Couturier said:
Hi,
suppose I have in an IEnumerable objet, records like this:
ColA, ColB
-------------
A, 1
A, 2
B, 1
B, 3
B, 4
How can I write my LINQ so that I get a list of 2 objects:
{
id = A
List<int>() = {1, 2}
},
{
id = B
List<int>() = {1, 3, 4}
}
The LINQ group clause creates an enumeration of IGrouping<TKey, TElement>
which, in turn is an IEnumerable<TElement> and has a .Key<TKey>. Hence the
code below creates an enumeration for IGrouping<string, int> where the Key
value comes from ColA and is an enumeration of all ColB values found for
that Key value:-
var a = new[] {
new { ColA = "A", ColB = 1 },
new { ColA = "A", ColB = 2 },
new { ColA = "B", ColB = 1 },
new { ColA = "B", ColB = 2 },
new { ColA = "B", ColB = 3 }
};
var x = from i in a
group i.ColB by i.ColA;
foreach (var g in x)
{
Console.WriteLine(g.Key);
foreach (var i in g)
Console.WriteLine("\t{0}", i);
}
This would probably suit you, however if you really do need, id and a
List<int> then:-
var x = from i in a
group i.ColB by i.ColA into g
select new { id = g.Key, list = g.ToList() };
foreach (var g in x)
{
Console.WriteLine(g.id);
foreach (var i in g.list)
Console.WriteLine("\t{0}", i);
}
The extra select allows you to create a projection of the required form.