我设计的方法接受List<Bar>
,并返回<List>BarGroup
,按Bar.barName
分组。我的猜测是我需要在List.Add中使用Aggregate,但我对lambdas和Linq的语法还是比较新的!
到目前为止我的代码:
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);
}
当我在LinqPad中尝试这个时,我得到以下结果:
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
但我正在寻找的是:
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
我认为Linq是这种分裂的最佳选择,但我对任何其他完成相同任务的方法持开放态度。
答案 0 :(得分:1)
尝试
var barGrouped = from b in bars
group b by b.barName into g
select new BarGroup()
{
barName = g.Key,
barList = g.ToList()
};
组IEnumerable<Bar>
满足分组标准。 bars是原始集合,这就是为什么在你的BarGroups中你可以获得所有项目。