使用Linq,如何对目标对象中的列表中的对象进行GroupBy

时间:2013-01-28 22:50:16

标签: c# linq grouping

可能措辞不对,但这就是我所拥有的,这是我想要实现的结果:

class Cake
{
public List<string> Ingrediants {get;set;}
public DateTime Baked {get;set;}
public string CakeName {get;set;}
}

List<Cake> cakes= new List<Cake>();
cakes.Add(new Cake() {CakeName = "Cake1", Ingrediants = new List<string>() {"Sugar", "Chocolate"}});
cakes.Add(new Cake() {CakeName = "Cake2", Ingrediants = new List<string>() {"Sugar", "Butter"}});
cakes.Add(new Cake() {CakeName = "Cake3", Ingrediants = new List<string>() {"Stevia", "Butter"}});

我想用杏仁分组蛋糕。所以我想最终得到这个:

 - Sugar
        Cake1
        Cake2
 - Stevia
        Cake3 
 - Chocolate
        Cake1
 - Butter
        Cake2
        Cake3

提前致谢!

3 个答案:

答案 0 :(得分:8)

如果你不介意查询理解,这里有另一种选择(注意更正的拼写):

IEnumerable<IGrouping<string,Cake>> query =
    from cake in cakes
    from ingredient in cake.Ingredients
    group cake by ingredient;

惊喜!这是一个有效的查询!语言规范允许理解以分组结尾。 IGrouping<string,Cake>在技术上是IEnumerable<Cake>,其Key属性类型为string - 在这种情况下是成分。编译器将其转换为几乎与其他答案完全相同的代码。

我们可以通过引入一个into和一个select子句来改变查询以生成与其他答案类似的相同泛型类型,该子句在查询延续中起作用:

var query =
    from cake in cakes
    from ingredient in cake.Ingredients
    group cake by ingredient into cakesGrouped
    select new { Ingredient = cakesGrouped.Key, 
        Cakes = cakesGrouped.ToList() };

流利的语法和查询语法都值得了解,恕我直言。干杯!

答案 1 :(得分:6)

var ingrediants = cakes.SelectMany(c => c.Ingrediants.Select(i => new { Cake = c, Ingrediant = i }))
    .GroupBy(ci => ci.Ingrediant)

然后组密钥是成分名称,组集合是匹配的蛋糕。

答案 2 :(得分:4)

这是一种方法:

var result = cakes
    .SelectMany(c => c.Ingrediants.Select(i => new
        {
            c.CakeName,
            Ingredient = i
        }))
    .GroupBy(x => x.Ingredient)
    .Select(g => new
        {
            Ingredient = g.Key,
            Cakes = g.Select(x=>x.CakeName).ToArray()
        });

result将是匿名类型的IEnumerable;一个代表成分的元素和包含它的所有Cakes。