How can I add an extra object to the results of a LINQ query?
I have the following code that needs to add an additional object after the results have been retrieved from the database. Any ideas on how I can go about doing this?
public IEnumerable<ProdPriceDisplay> GetShopProductsPrices()
{
//ProdPriceDisplay ProdPrice = new ProdPriceDisplay();
var Products = from shop in db.SHOPs
select new ProdPriceDisplay
{
ProdPrice = shop.S_NAME + " - £" + shop.S_PRICE
};
// *** Want to add something like this:-
// Products.Add new ProdPriceDisplay { ProdPrice = "some additional text"; }
return Products;
}
source to share
Use Enumerable.Concat
:
public IEnumerable<ProdPriceDisplay> GetShopProductsPrices()
{
var products = from shop in db.SHOPs
select new ProdPriceDisplay
{
ProdPrice = shop.S_NAME + " - £" + shop.S_PRICE
};
return products.AsEnumerable()
.Concat(new [] { new ProdPriceDisplay
{ ProdPrice = "some additional text"; });
}
The advantage of doing this conversion on a list is that the results are still streamed, so you don't get a complete copy of the data.
EDIT: you can use instead of an array if you like - but not much use.Enumerable.Repeat
(new ProdPriceDisplay { ... }, 1)
EDIT: I've added a call AsEnumerable()
that basically says "At this point we don't want to do the rest of the operations on the database - make them local."
source to share