Reputation: 77
Im designing a method that accepts a List<Bar>
, and returns <List>BarGroup
, grouped by Bar.barName
. My guess is I need to use Aggregate with List.Add, but I am fairly new to lambdas and Linq's syntax!
My code so far:
public class BarGroup
{
public string barName;
public List<Bar> barList;
}
public class Bar
{
public string barName;
public string fooDetails;
public Bar(string b, string f)
{
this.barName = b;
this.fooDetails = f;
}
}
void Main()
{
Bar bar1 = new Bar("BarGroup1","Bar1");
Bar bar2 = new Bar("BarGroup1","Bar2");
Bar bar3 = new Bar("BarGroup2", "Bar3");
Bar bar4 = new Bar("BarGroup2", "Bar4");
List<Bar> bars = new List<Bar> { bar1, bar2, bar3, bar4 };
var barGrouped = from b in bars
group b by b.barName into g
select new BarGroup()
{
barName = g.Key,
barList = bars
};
Console.WriteLine(barGrouped);
}
When I try this in LinqPad, I get the following result:
IEnumerable<BarGroup> (2 items)
barName barList
BarGroup1 List<Bar> (4 items)
barName fooDetails
BarGroup1 Bar1
BarGroup1 Bar2
BarGroup2 Bar3
BarGroup2 Bar4
BarGroup2 List<Bar> (4 items)
barName fooDetails
BarGroup1 Bar1
BarGroup1 Bar2
BarGroup2 Bar3
BarGroup2 Bar4
But what I'm looking for is below:
IEnumerable<BarGroup> (2 items)
barName barList
BarGroup1 List<Bar> (4 items)
barName fooDetails
BarGroup1 Bar1
BarGroup1 Bar2
BarGroup2 List<Bar> (4 items)
barName fooDetails
BarGroup2 Bar3
BarGroup2 Bar4
I assumed Linq was the best choice for this type of splitting, but I am open to any other methods that accomplish the same task.
Upvotes: 0
Views: 403
Reputation: 23551
Try
var barGrouped = from b in bars
group b by b.barName into g
select new BarGroup()
{
barName = g.Key,
barList = g.ToList()
};
The group is IEnumerable<Bar>
that satisfy the grouping criteria. bars is the original collection and this is why in your BarGroups you get all the items.
Upvotes: 1