Search code examples
c#linq

Correct way to loop and stop when value is found inside json object


I'm trying to get a page within this JSON, I'm getting the value I want but its becoming null because the loop will not stop and go to other section without the correct value. What is the best way to get a page here and stop the loop when the value is found?

code

   var pageId = 912;

   foreach(var section in SectionsObj)
        {
            page = section.Pages.Where(page => page.PageId == pageId).FirstOrDefault();      
        };

json

{
   "sections":[
      {
         "sectionId":1,
         "sectionName":"xxx",
         "pages":[
            {
               "pageId":910,
               "pageName":"Profile Page 1"
            },
            {
               "pageId":911,
               "pageName":"Profile Page 2"
            }
         ]
      },
      {
         "sectionId":2,
         "sectionName":"xx",
         "pages":[
            {
               "pageId":912,
               "pageName":"Profile Page 1"
            },
            {
               "pageId":913,
               "pageName":"Profile Page 2"
            }
         ]
      },
      {
         "sectionId":3,
         "sectionName":"xxxx",
         "pages":[
            {
               "pageId":914,
               "pageName":"Profile Page 1"
            },
            {
               "pageId":915,
               "pageName":"Profile Page 2"
            }
         ]
      }
   ]
}

Solution

  • As per my comment, you can shorten the code to be:

    var page = SectionsObj.SelectMany(s => s.Pages).FirstOrDefault(p => p.PageId == pageId);