不太正确,但这是我所拥有的,这是我想要实现的结果:
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
提前感谢!
如果您不介意查询推导,这里有一个替代方案(注意更正的拼写):
IEnumerable<IGrouping<string,Cake>> query =
from cake in cakes
from ingredient in cake.Ingredients
group cake by ingredient;
惊喜!这是一个有效的查询!语言规范允许理解以分组依据结束。从技术上讲,IGrouping<string,Cake>
是一种具有string
型Key
特性的IEnumerable<Cake>
- 在这种情况下是成分。编译器致力于将其转换为与其他答案几乎相同的代码。
我们可以通过引入一个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() };
恕我直言,流畅的语法和查询语法都值得了解。干杯!
var ingrediants = cakes.SelectMany(c => c.Ingrediants.Select(i => new { Cake = c, Ingrediant = i }))
.GroupBy(ci => ci.Ingrediant)
然后组键是成分名称,组集合是匹配的蛋糕。
这里有一种方法可以做到这一点:
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
;一个元素代表一种成分和所有包含它的蛋糕。