LINQ选择值列表并映射到嵌套类结构中的一个字段属性

时间:2016-11-29 10:04:13

标签: c# linq

动物

+----------+---------+--------+
| animalId | animal  | typeId |
+----------+---------+--------+
|    1     | snake   |   1    |
|    2     | cat     |   2    |
+----------+---------+--------+

AnimalType:

+--------+----------+
| typeId |   type   |
+--------+----------+
|   1    | reptile  |
|   2    | mammal   |
+--------+----------+

AnimalBody:

+--------+-------+----------+
| bodyId | body  | animalId |
+--------+-------+----------+
|    1   | tail  |    1     |
|    2   | eye   |    1     |
|    3   | tail  |    2     |
|    4   | eye   |    2     |
|    5   | leg   |    2     |
+--------+-------+----------+

表关系:

  • Animal.typeId = AnimalType.typeId
  • Animal.animalId = AnimalBody.animalId

我需要将它们输出为JSON格式,如下所示:

{
   animalId: 1,
   animal: "snake",
   type: "reptile",
   body: {
      "tail", "eye"
   }
}, 
{
   animalId: 2,
   animal: "cat",
   type: "mammal",
   body: {
      "tail", "eye", "leg"
   }
}

如何使用纯LINQ子句而不是方法实现此目的?

我尝试过:

from animal in db.Animal 
join animalType in db.AnimalType on animal.typeId equals animalType.typeId
select new 
{
   animalId = animal.animalId,
   animal = animal.animal,
   type = animalType.type,
   body = ?
};

1 个答案:

答案 0 :(得分:2)

假设您希望body元素是一个正文部分数组,那么您应该做什么: 使用Animal s加入AnimalType

var animalsWithType = db.Animals.Join(
    animal => animal.typeId,
    animalType => animalType.typeId,
    (animal, type) => new { animal, type });

之后,GroupJoin animalsWithType带有AnimalBody元素:

var result = animalsWithType.GroupJoin(db.AnimalBodies,
    animalWithType => animalWithType.animal.animalId,
    body => body.animalId,
    (animalWithType, bodyParts) => new
    {
        animalId = animalWithType.animal.animalId,
        animal = animalWithType.animal.animal,
        type = animalWithType.type.type,
        body = bodyParts.Select(part => part.body)
    });

现在,只需将result导出到JSON即可设置。