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

Time:10-06

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"
            }
         ]
      }
   ]
}

CodePudding user response:

Put the logic inside a function and return when you find the page:

var pageId = 912;

var page = FindPage(pageId, SectionsObj);

private Page FindPage(int id, IEnumerable<Section> sections)
{
    foreach(var section in sections)
    {
        page = section.Pages.FirstOrDefault(page => page.PageId == id);
        if (page != null)
        {
            return page;
        }
    }
    return null;
}
   

CodePudding user response:

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

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