views:

26

answers:

1

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?

+3  A: 

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;
Jon Skeet
Do you think that performace-wise is better to serialize the object and do the LINQ to XML. I have the object structure already cached.
the berserker
It's unlikely that it's worth serializing back to XML, but you haven't shown what your object structure is like. I expect it wouldn't be hard to do something similar - particularly if they're partial classes so you can add a recursive call into Category.
Jon Skeet