title: Insert XAttribute to existing XElement at specified position
body: <p>Here is simplified use case code example for creating element with attributes</p>
  
  <pre><code>        XElement element =
              new XElement(
                  "Test",
                  new XAttribute("Attr1", "value1"),
                  new XAttribute("Attr3", "value3")
              );
  
          element.Add(new XAttribute("Attr2", "value2"));
  </code></pre>
  
  <p>How to achieve that Attr2 is added after Attr1 to produce output like this?</p>
  
  <pre><code>        &lt;Test Attr1="value1" Attr2="value2" Attr3="value3" /&gt;
  </code></pre>
  
  <p>Any help is appreciated. Thank you</p>
  
  <p><strong>Here is the extension method mentioned in accepted answer:</strong></p>
  
  <pre><code>public static void AddAfterSelf(this XAttribute self, XAttribute value)
  {
      if (self == null) throw new ArgumentNullException("self");
      if (value == null) throw new ArgumentNullException("value");
      if (self.Parent == null) throw new ArgumentException("Attribute does not belong to any element.");
  
      XElement e = self.Parent;
      var attributes = new List&lt;XAttribute&gt;(e.Attributes());
      int idx = attributes.IndexOf(self);
  
      attributes.Insert(idx + 1, value);
      e.RemoveAttributes();
      e.Add(attributes);
  }
  </code></pre>