0

我正在设计一种方法,该方法接受 aList<Bar>并返回<List>BarGroup,按Bar.barName. 我的猜测是我需要将 Aggregate 与 List.Add 一起使用,但我对 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 是此类拆分的最佳选择,但我对完成相同任务的任何其他方法持开放态度。

4

1 回答 1

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>满足分组标准的。bar 是原始集合,这就是为什么在您的 BarGroups 中获得所有项目的原因。

于 2013-04-07T02:18:52.917 回答