6

可能措辞不太正确,但这就是我所拥有的,这是我想要达到的结果:

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

提前致谢!

4

3 回答 3

8

如果您不介意查询理解,这里有一个替代方案(注意更正的拼写):

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

惊喜!这是一个有效的查询!语言规范允许理解以 group-by 结尾。从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() };

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

于 2013-01-29T04:27:06.563 回答
6
var ingrediants = cakes.SelectMany(c => c.Ingrediants.Select(i => new { Cake = c, Ingrediant = i }))
    .GroupBy(ci => ci.Ingrediant)

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

于 2013-01-28T22:57:25.930 回答
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匿名类型;一个元素代表一种成分和所有包含它的蛋糕。

于 2013-01-28T22:56:04.563 回答