Why is it when I do this:
private void button18_Click(object sender, EventArgs e)
{
string uri1 = "http://localhost:8000/Service/GetMessage/{anything}";
string tagUri = uri1.Replace("{anything}", textBox21.Text);
XDocument xDoc = XDocument.Load(tagUri);
var MessageID = xDoc.Descendants("Message")
.Select(n => new
{
MessageID = n.Element("MessageID").Value,
})
.ToString();
textBox1.Text = MessageID;
I get this really strange output?
System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Xml.Linq.XElement,<>f__AnonymousType7`1[System.String]]
But yet when I change ToString to ToList and use:
dataGridView10.DataSource = MessageID;
It displays it correctly? Really struggling to find out a way to take my incoming GET request to string?
Your LINQ query is getting a collection by nature of the call to .Descendants
. If there's only one, you can use a .Single()
or .First()
or .FirstOrDefault()
to get the only (or First) item in the list.
Then it would be
textbox1.Text = MessageID.MessageID;
Though you more likely want to do something like this:
var MessageId = xDoc.Element("Message").Element("MessageID").Value;
But I'm somewhat guessing, as I don't know the format or content of your XML.
There are others here who can give you a more detailed explanation, but here's what I think is happening (expanded from my comment above).
By default, LINQ queries return a collection, even when there's only one result. When you call .ToString()
on the that collection, you get the fully qualified name of the type of the Object. See Object.ToString Method - which in this case I believe is the weird output you get.
You're probably looking for a single result (MessageID), so you could use .FirstOrDefault()
instead of .ToString()
, like this:
var MessageID = xDoc.Descendants("Message")
.Select(n => new
{
MessageID = n.Element("MessageID").Value,
})
.FirstOrDefault();
Note that n.Element("MessageID").Value
will return a string, which you can then assign to the TextBox.
When you convert the query to a List, you are able to bind it to the DataGridView's DataSource because DataSource takes objects that implement one of the IList
interfaces ( IList
in the case of a generic list).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.