Linq Query to Update Nested Array Items?

Posted by Brett on Stack Overflow See other posts from Stack Overflow or by Brett
Published on 2010-05-18T17:46:07Z Indexed on 2010/05/18 17:50 UTC
Read the original article Hit count: 471

Filed under:

I have an object structure generated from xsd.exe. Roughly, it consists of 3 nested arrays: protocols, sources and reports. The xml looks like this:

<protocols>
  <protocol>
    <source>
      <report />
      <report />
    </source>
    <source>
      <report />
      <report />
    </source>
  </protocol>
  <!-- more protocols -->
</protocols>

I need to update a single "Report" within the data structure. A brute force algorithm is shown below. I know that this could be done using XDocument and Linq, but I'd prefer to update the data structure and then serialize the structure back to disk.

Thoughts?

Brett

bool updated = false;
foreach (ProtocolsProtocol protocol in protocols.Protocol)
{
    if (updated)
        break;
    foreach (ProtocolsProtocolSource source in protocol.Source)
    {
        if (updated)
            break;
        for (int i = 0; i < source.Report.Length; i++)
        {
            ProtocolsProtocolSourceReport currentReport = source.Report[i];
            if (currentReport.Id == report.Id)
            {
                currentReport.Attribute1 = report.Attribute1;
                currentReport.Attribute2 = report.Attribute2;
                updated = true;
                break;
            }
        }
    }
}

© Stack Overflow or respective owner

Related posts about linq-to-objects