Linq to XML: create an anonymous object with element attributes and values
        Posted  
        
            by Phil Scholtes
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Phil Scholtes
        
        
        
        Published on 2010-05-17T01:14:12Z
        Indexed on 
            2010/05/17
            1:20 UTC
        
        
        Read the original article
        Hit count: 509
        
I'm new to Linq and I'm trying to query a XML document to find a list of account managers for a particular user. (I realize it might make more sense to put this in a database or something else, but this scenario calls for a XML document).
<user emailAddress='[email protected]'>
    <accountManager department='Customer Service' title='Manager'>[email protected]</accountManager>
    <accountManager department='Sales' title='Account Manager'>[email protected]</accountManager>
    <accountManager department='Sales' title='Account Manager'>[email protected]</accountManager>
</user>
I trying to create a list of objects (anonymous type?) with properties consisting of both XElement attributes (department, title) and values (email). I know that I can get either of the two, but my problem is selecting both.
Here is what I'm trying:
var managers = _xDoc.Root.Descendants("user")
               .Where(d => d.Attribute("emailAddress").Value == "[email protected]")
               .SelectMany(u => u.Descendants("accountManager").Select(a => a.Value));
foreach (var manager in managers)
{
     //do stuff
}
I can get at a.Value and a.Attribute but I can't figure out how to get both and store them in an object. I have a feeling it would wind up looking something like:
select new { 
    department = u.Attribute("department").Value,
    title = u.Attribute("title").Value,
    email = u.Value
};
© Stack Overflow or respective owner