So I’m just starting out with ASP.NET MVC, and I’ve run into an issue I just can’t find an answer to.
I’m grabbing some data from an SQL database, and send it to the view with this code:
var listingsQuery = (from s in db.tblListings select s).OrderBy(s => s.listingID).Skip(100).Take(25);
var listings = listingsQuery.ToList();
return View(listings);
This works great, but I want to add a value in the list of results. Basically what I’m trying to do is something like this:
foreach (var item in listings)
{
this.Add("propertyType", "Home");
}
But obviously that doesn’t work. I’ve tried doing ToArray() instead of ToList() and that got me nowhere.
Do you want to add a new property to each object in the List collection? If so, you can create a new type that inherits from whatever object type is in the list (hover over the listingsQuery variable – the type is inside the <> symbols) and add the new property to it:
Then inside of your query, project the properties into this new type:
Now you can cycle through each record and assign a value:
There are other ways of doing this as well (assuming you’re using EF), for example, if you used raw SQL you can cast the result type directly into the new type (without having the map each field), but this should get you started.