开发者

querying nested array elements in C#

开发者 https://www.devze.com 2022-12-26 11:32 出处:网络
I have following object structure, deseralized from XML (WS): <ns2:Category> <ns2:CategoryId>800003</ns2:CategoryId>

I have following object structure, deseralized from XML (WS):

<ns2:Category>
  <ns2:CategoryId>800003</ns2:CategoryId>
  <ns2:CategoryName>Name1</ns2:CategoryName>
  <ns2:Categories>
    <ns2:Category>
      <ns2:CategoryId>800008</ns2:CategoryId>
      <ns2:CategoryName>Name2</ns2:CategoryName>
      <ns2:Categories>
        <ns2:Category>
          <ns2:CategoryId>800018</ns2:CategoryId>
          <ns2:CategoryName>Name3</ns2:CategoryName>
          <ns2:Categories/>
        </ns2:Category>
        <ns2:Category>
          <ns2:CategoryId>800028</ns2:CategoryId>
          <ns2:CategoryName>Name4</ns2:CategoryName>
          <ns2:Categories/>
        </ns2:Category>
      </ns2:Categories>
    </ns2:Category>
    <ns2:Category>
      <ns2:CategoryId>800009</ns2:CategoryId>
      <ns2:CategoryName>Name5</ns2:CategoryName>
      <ns2:Categories>
        <ns2:Category>
          <ns2:CategoryId>800019</ns2:CategoryId>
          <ns2:CategoryName>Name6</ns2:CategoryName>
          <ns2:Categories>
            <ns2:Category>
              <ns2:CategoryId>800119</ns2:CategoryId>
              <ns2:CategoryName>Name7</ns2:CategoryName>
              <ns2:Categories/>
            </ns2:Category>
            <ns2:Category>
              <ns2:CategoryId>800219</ns2:CategoryId>
              <ns2:CategoryName>Name111</ns2:CategoryName>
              <ns2:Categories/>
            </开发者_开发百科ns2:Category>
          </ns2:Categories>
        </ns2:Category>
      </ns2:Categories>
    </ns2:Category>
  </ns2:Categories>
</ns2:Category>

How would I find Category object with CategoryId 800119 efficiently? So, Im looking for something like FindCategory(long categoryId) - Prefferably with LINQ to objects. Any other option?


I'd use LINQ to XML:

XNamespace ns = "http://url-for-ns2";
XDocument doc = XDocument.Load("file.xml");

string requiredId = "800119";
var categoryId = doc.Desendants(ns + "CategoryId")
                    .Where(x => x.Value == requiredId)
                    .FirstOrDefault();
var category = categoryId == null ? null : categoryId.Parent;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号