如何通过x.Something1和x.Something2来“查询语法”组“ x”?

时间:2019-04-20 12:12:04

标签: c# linq

我正在练习LINQ查询语法和方法语法,以学习如何将表达式转换为另一种语法。

我在如何将此方法语法转换为查询语法方面遇到问题。

  var groupNew = dogs.GroupBy(x =>new { x.Color, x.Breed});
  var groupNew2 = groupNew.SelectMany(x => x);

输出:

Method Syntax Output

这是我编码的查询语法,我认为它可以工作,但编译器不接受。

var groupQuery = from d in dogs
                 group d by d.Color and d.Breed into newGroup
                 select new { age = newGroup.Key, color = d.Color, breed = d.breed };

如果我正确地测试了新类型,则新类型只会从查询中返回年龄,这与方法语法不同。

测试数据:

Dog[] dogs = new Dog[] {
            new Dog(2, "Poms", "Green"),
            new Dog(10, "Poms", "Green"),
            new Dog(3, "Poms", "Green"),
            new Dog(4, "Askal", "White"),
            new Dog(2, "Askal", "Black"),
            new Dog(2, "German", "Brown"),
            new Dog(2, "Shitsu", "White"),
            new Dog(3, "Dalgom", "Brown"),
            new Dog(1, "Dalgom", "Brown"),
            new Dog(2, "Dalgom", "Black"),
            new Dog(4, "Chiwawa", "Blackpink"),
            new Dog(3, "Chiwawa", "Blackpink"),

        };

1 个答案:

答案 0 :(得分:2)

这是查询语法中的LINQ查询:

var groupNew = from dog in dogs // GroupBy
               group dog by new { dog.Color, dog.Breed } into groups
               select groups;
var groupNew2 = from g in groupNew // SelectMany
                from dog in g
                select dog;

或在单个查询中:

var groupNew2 = from g in (
                  from dog in dogs
                  group d by new { d.Color, d.Breed } into groups
                  select groups
                )
                from dog in g
                select dog;