tags:

views:

68

answers:

3

I have the following code that I need to add an additonal object to after the results have been retrieved from the databse. Any Ideas on how I might to 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;
}
A: 

That could be a solution;

var productsAsList = Products.ToList();
productsAsList.Add(new ProdPriceDisplay { ProdPrice = "some additional text"; });

return productsAsList; // As your return type is IEnumarable, that won't be a problem;
yapiskan
This has also been useful to me - thanks.
Ebircsa
Yes this is a solution but I recommend the Jon's as he mentioned its benefits.
yapiskan
+1  A: 

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 benefit of this over converting to a list is that the results are still streamed, so you don't end up taking a complete copy of the data.

EDIT: You could use Enumerable.Repeat (new ProdPriceDisplay { ... }, 1) instead of the array if you wanted to - but there's not a lot of benefit.

EDIT: I've added the call to AsEnumerable() which basically says, "At this point, we don't want to do the rest of the operations in the database - make them local."

Jon Skeet
This one is really nice.
yapiskan
Thanks for this - I'll give it a go.
Ebircsa
Great, that works - Thanks Jon.
Ebircsa
A: 

Have tried using the Enumerable.Concat method but get the following error:-

"Local sequence cannot be used in a LINQ to SQL implementation of query except the Contains() opertaor".

Any idea why this might be happening ?

Ebircsa
Ah, yes - it's trying to keep it on the database. Will edit my answer.
Jon Skeet