Linq and groups

  • Thread starter Thread starter Mike Gleason jr Couturier
  • Start date Start date
M

Mike Gleason jr Couturier

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}
}

Thanks!
 
Mike said:
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} }

Here's a sample I just put together. My Linq experience is minimal :-)

public class MyData
{
public string ColA;
public int ColB;
}

public void LinqTest()
{
List<MyData> data = new List<MyData>();
data.Add(new MyData() { ColA = "A", ColB = 1 });
data.Add(new MyData() { ColA = "A", ColB = 2 });
data.Add(new MyData() { ColA = "B", ColB = 1 });
data.Add(new MyData() { ColA = "B", ColB = 3 });
data.Add(new MyData() { ColA = "B", ColB = 4 });

var result =
from d in data
group d by d.ColA into ColBList
select new
{
id = ColBList.Key,
Count = ColBList.Count(),
Values =
from values in ColBList
select values.ColB
};

foreach (var item in result)
{
string key = item.id;
List<int> values = item.Values.ToList<int>();
}
}
 
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.
 
Back
Top