I’ve an Xml file like
<SampleFile>
<Data>
<Element Val="8" />
<Element Val="10" />
<Element Val="12" />
<Element Val="14" />
<Element Val="16" />
<Element Val="9" />
<Element Val="11" />
<Element Val="13" />
<Element Val="15" />
<Element Val="17" />
</Data>
</SampleFile>
i need to read the attribute value of” Val” and convert it to Int32 , then sort and then add to the list
now i’m using like:
List<Int32> lst = (XDocument.Load("\\Sample.xml").Descendants("Element").Select(l_Temp => l_Temp.Attribute("Val").Value.ToString()).Cast<Int32>().OrderBy(nTemp => nTemp)).ToList();
but its not working properly
please give me a better solution
First let’s reformat the code a bit so we can actually see what’s going on:
Now, your
Selectclause is selecting a sequence of strings – although theToStringcall is unnecessary asXAttribute.Valueis already a string.You’re then trying to use
Cast<Int32>to convert those strings into integers. That’s not whatCast<T>()does. It only performs reference an unboxing conversions. Fortunately,XAttributehas an explicit conversion tointwhich makes all of this much simpler: