C#Linq在嵌套数组对象中查找特定项

c#

我正在使用 asp.net core webapi 和 azure cosmosdb 开发应用程序。我需要从对象列表中找到一个项目。我对 linq 没有经验。在下面的 json 中,我需要找到一个拥有 learnerId": "123" 的部门 id。我期待输出如下:

"id": "7d65fa4c-86ed-4e07-9e9a-a1583df5715c"

部门:

[
  {
    "name": "Emp1",
    "edsNumber": "",
    "sectors": [
      {
        "id": "7d65fa4c-86ed-4e07-9e9a-a1583df5715c",
        "name": "Technology1",
        "learners": [
          {
            "learnerId": "123",
            "learnerName": "Learner1",
            "dateAdded": 1612872051
          },
          {
            "learnerId": "456",
            "learnerName": "Learner2",
            "dateAdded": 1612877369
          },
          {
            "learnerId": "789",
            "learnerName": "Learner3",
            "dateAdded": 1612877372
          },
          {
            "learnerId": "12314",
            "learnerName": "Learner4",
            "dateAdded": 1613065233
          },
          {
            "learnerId": "2346",
            "learnerName": "Learner5",
            "dateAdded": 1613577350
          }
        ],
        "course": {
          "name": "Angularv10",
          "isCompleted": true
        },
        "contact": {
          "name": "Voytek",
          "jobTitle": "Designer1",
          "email": "rana@gmail.com",
          "isCompleted": true
        }
      }
    ]
  },
  {
    "name": "Emp2",
    "edsNumber": "",
    "sectors": [
      {
        "id": "7d65fa4c-86ed-4e07-9e9a-a1583df5235c",
        "name": "Technology1",
        "learners": [
          {
            "learnerId": "834457",
            "learnerName": "Learner6",
            "dateAdded": 1612872051
          },
          {
            "learnerId": "11122",
            "learnerName": "Learner7",
            "dateAdded": 1612877369
          }
        ],
        "course": {
          "name": "Angularv10",
          "isCompleted": true
        },
        "contact": {
          "name": "Voytek",
          "jobTitle": "Designer1",
          "email": "rana@gmail.com",
          "isCompleted": true
        }
      }
    ]
  }
]

我尝试了以下方法:

        var sectorId = (from e in employers
                      from s in e.Sectors
                      from l in s.Learners
                      where l.LearnerId == learnerEntity.Id
                      select s.Id).FirstOrDefault();

有没有更好的方法来实现?以及如何同时获得 SectorId 和该部门所属的雇主?

回答

查找满足子对象条件的单个项目的 LINQ 查询将有两个组件:

  • 调用SingleOrDefault(或者Single如果您要查找的项目必须在那里),以及
  • 调用Any嵌套在第一个条件中以查看子项是否存在。

由于您的部门嵌入在雇主内部,您可以使用SelectMany.

这是它的外观:

var sectorId = employers
    .SelectMany(e => e.Sectors) // Flatten sectors
    .SingleOrDefault(
        s => s.Learners.Any(sl => sl.Id == targetId)
    ).Id;


以上是C#Linq在嵌套数组对象中查找特定项的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>