Reputation: 3965
I'm using the following code to grab data from an XML document:
XDocument xml = XDocument.Load(xmlPath);
var bikes = from b in xml.Descendants("Photo")
select new
{
date = (DateTime)b.Element("Date"),
staffno = (Int32)b.Element("StaffNo"),
file = (string)b.Element("File"),
crimeref = (string)b.Element("CrimeRef")
};
If I use something like var selectedBikes = bikes.Count();
, I can see there are 4 bikes in total. However I'm not sure how to actually get that data into a list so that I can display it on my view using Razor.
I've tried bikes.Select()
, bikes.All()
and a few others but haven't had any joy.
Upvotes: 0
Views: 44
Reputation: 103525
var lstBikes = bikes.ToList(); // or .ToArray(); your choice.
Now, bikes
as it is, is an IEnumerable
, so you can just passed that to the view. You'll probably also want to define a Photo
class, and use it like this:
class Photo
{
DateTime date {get; set;}
Int32 staffno {get; set;}
string file {get; set;}
string crimeref {get; set;}
};
// :
var bikes = from b in xml.Descendants("Photo")
select new Photo
{
date = (DateTime)b.Element("Date"),
staffno = (Int32)b.Element("StaffNo"),
file = (string)b.Element("File"),
crimeref = (string)b.Element("CrimeRef")
};
Then you can say @model IEnumerable<Photo>
in your view.
Upvotes: 2
Reputation: 684
Sorry if I am mistaken because haven't worked with xml files for a while, but usually LINQ returns a IEnumerable<> object. So if you want to use it as a list you can get it as bikes.ToList()
/ Which will enumerate your object you should keep that in mind /. Also, if you are not going to add/remove items from the IEnumerable object in the view (which is not a good idea usually, keep your logic outside of your view and just display data there) you can simple iterate through the result with a foreach loop.
Upvotes: 2