链接到对象和到列表

本文关键字:列表 对象 链接 | 更新日期: 2023-09-27 18:07:44

我正在设计一个方法,它接受一个List<Bar>,并返回按Bar.barName分组的<List>BarGroup。我的猜测是我需要使用聚合与列表。添加,但我对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是这种类型的分割的最佳选择,但我对完成相同任务的任何其他方法都持开放态度。

链接到对象和到列表

Try

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中您可以获得所有项目的原因。