2008-11-18 66 views
0

我有下面的代码,我需要添加一个额外的对象来从数据库检索结果后。任何想法,我可能如何呢?如何将其他对象添加到LINQ查询的结果中?

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; 
} 

回答

1

使用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"; }); 
} 

该上转换到一个列表的好处是,结果仍然流,这样你就不会最终获取数据的完整副本。

编辑:你可以使用Enumerable.Repeat(new ProdPriceDisplay { ... }, 1)而不是数组,如果你想 - 但没有太多的好处。

编辑:我添加了电话AsEnumerable(),基本上说,“在这一点上,我们不希望在数据库中做其余的操作 - 使他们本地。”

0

这可能是一个解决方案;

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; 
+0

这对我也很有用 - 谢谢。 – Ebircsa 2008-11-18 10:46:55

+0

是的,这是一个解决方案,但我建议Jon的,因为他提到了它的好处。 – 2008-11-18 12:08:51