0

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.

2 Answers 2

3

Just change

textBox.Text = comm;

to

textBox.Text = comm.FirstOrDefault();
Sign up to request clarification or add additional context in comments.

4 Comments

comm is an XElement, not an IEnumerable<XElement> because he is using Element("comment").
Actually comm IS an IEnumerable<XElement>, and that was my issue.
@Dave: It's actually IEnumerable<string>... it was projected to the Value of the XElement.
@DaveShaw: No, comm is an IEnumerable<string>. comment.Element("comment").Value is only in the select part of the linq query!
1

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 = "";
}

4 Comments

Is .Value == tagBox.Text valid in the LINQ expression? I would have thought .Contains(tagBox.Text) would be the way to put run-time values into the query.
@DaveShaw, you're right, I forgot to remove it. The whole semantics of the code weren't right anyway so I changed it all around.
@Tim: they're both possible, but they are semantically different. "==" is exact match, and ".Contains()" would be more of a wildcard match. If you want to specify culture and have an exact match I'd use ".Equals()"
@Mr Happy - thanks for the info. I didn't realize the differences. Good stuff to know.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.