Following on from a previous question, I have the following code:
var results =
from result in xml.Descendants(ns + "GetMetalQuoteResult")
select new
{
Type = result.Element(ns + "Type").Value,
Currency = result.Element(ns + "Currency").Value,
Date = result.Element(ns + "Date").Value,
Time = result.Element(ns + "Time").Value,
Rate = (decimal)result.Element(ns + "Rate"),
Bid = (decimal)result.Element(ns + "Bid"),
BidTime = result.Element(ns + "BidTime").Value,
ExpTime = result.Element(ns + "ExpTime").Value,
DisplayTime = result.Element(ns + "DisplayTime").Value,
DisplayDate = result.Element(ns + "DisplayDate").Value,
Ask = (decimal)result.Element(ns + "Ask"),
AskTime = result.Element(ns + "AskTime").Value,
};
How do I access these elements?
e.g. If I want to gain access to the value of element ‘Ask’, why can’t I just use the following code.
System.Diagnostics.WriteLine(results.Ask);
Am I doing something stupidly wrong because I am getting the following error
Error 2 'System.Collections.Generic.IEnumerable<AnonymousType#1>' does not contain a definition for 'Ask' and no extension method 'Ask' accepting a first argument of type 'System.Collections.Generic.IEnumerable<AnonymousType#1>' could be found (are you missing a using directive or an assembly reference?)
I was wrapped up in the context for a moment there, but your issue lies in that
resultsis a collection, so you can’t do that – you need to do it on one item of the collection:I could have picked a number of other extension methods to do this other than
Firstand would do it differently anyway, that’s an example. You should first check whether or not your collection contains any items and retrieve accordingly.Alternatively, and for the sake of demonstration, you could just loop through the results: