Reputation: 520
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 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
.
Upvotes: 0
Views: 1734
Reputation: 961
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 = "";
}
Upvotes: 1
Reputation: 3956
Just change
textBox.Text = comm;
to
textBox.Text = comm.FirstOrDefault();
Upvotes: 3