I’ve got a class:
public class Layout
{
public int Width { get; set; }
public int Height { get; set; }
}
How do I read the XML attribute and assign it to int from the class above in the following LINQ query:
var layouts =
from elem in layoutSummary.Descendants("Layout")
select new Layout
{
// Width = elem.Attribute("Width").Value, // Invalid cast string to int)
// Int32.TryParse((string)elem.Attribute("Height").Value, Height) // Doesn't assign Height value to Layout.Height
};
Try this instead:
This uses the explicit conversion operator available from
XAttributetoint, whose MSDN page you can find here.Now obviously, this will throw a
FormatExceptionif the conversion doesn’t succeed. If that’s not what you want, please indicate what you would like to happen. It is possible (if somewhat inconvenient) to useint.TryParsehere, but it would have to be done differently.