1

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"
            }
         ]
      }
   ]
}
user10860402
  • 912
  • 1
  • 10
  • 34
  • 1
    Why not `var page = SectionsObj.SelectMany(s => s.Pages).FirstOrDefault(p => p.PageId == pageId)`? – Hayden Oct 04 '22 at 11:46
  • Also, if you want to exit a loop early, use `break` or `return` in a method (as shown in Anderson's answer). – Hayden Oct 04 '22 at 11:51
  • @Hayden i used your answer because i want it to be shorted code, do you want to put that as an answer so i can mark it? also, do you have a "select" version of that expression? i just want to know how to use select and select many. – user10860402 Oct 04 '22 at 12:11
  • See: https://stackoverflow.com/questions/2641347/short-circuit-array-foreach-like-calling-break/2641374#2641374 – Matthijs Oct 04 '22 at 12:13

2 Answers2

2

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;
}
   
Anderson Pimentel
  • 5,086
  • 2
  • 32
  • 54
0

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

var page = SectionsObj.SelectMany(s => s.Pages).FirstOrDefault(p => p.PageId == pageId);
Hayden
  • 2,902
  • 2
  • 15
  • 29