I'm trying to make a Linq query that will retrieve a string value from an XML file and place it in a TextBox. I think I need to use FirstorDefault()
, but I can't figure out how to use it properly. Here is what I have at the moment:
var comm = from comment in xdoc.Descendants("string")
where comment.Attribute("id").Value == tagBox.Text
select comment.Element("comment").Value;
textBox.Text = comm; //Essentially
Basically, my XML file 开发者_StackOverflow社区looks like this:
<root>
<string id = "STRING_ID1">
<element1 />
<comment> Some string </comment>
...
</string>
</root>
In the first code snippet, tagBox refers to another TextBox that has a string in it which was originally pulled from the id
attribute of my string
element. The idea is to scan the XML for the matching ID, and simply put the value of the comment
element in the textBox
.
Just change
textBox.Text = comm;
to
textBox.Text = comm.FirstOrDefault();
Usage of FirstOrDefault would be as follows
var str = (from str in xdoc.Descendants("string")
where str.Attribute("id").Value == tagBox.Text
select str).FirstOrDefault();
if(str != null)
{
textBox.Text = str.Element("comment").Value;
}
else
{
textBox.Text = "";
}
精彩评论