Click here to Skip to main content
16,019,740 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi friends, i used following linq statements to avoid the foreach statement

linq
XmlNode node = (from XmlNode x in ThisAddIn.XmlNodesModelStyles where styleName == x.Attributes["name"].Value select x);


foreach
C#
foreach (XmlNode xNode in ThisAddIn.XmlNodesModelStyles)
    if (xNode.Attributes["name"].Value == styleName)
    { node = xNode; break; }


it shows the Maching cast error. how to solve this.

What I have tried:

convert the code from foreach statement to linq
Posted
Updated 13-Jun-16 3:44am
Comments
CHill60 13-Jun-16 9:06am    
What is styleName declared as?

1 solution

That Linq select doesn't return an XmlNode, it returns a IEnumerable<XmlNode> - so you can't just store it a in node variable.
Try adding .FirstOrDefault:
C#
XmlNode node = (from XmlNode x in ThisAddIn.XmlNodesModelStyles where styleName == x.Attributes["name"].Value select x).FirstOrDefault();
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900