如何在LINQ查询的结果中添加其他对象?

时间:2008-11-18 09:52:37

标签: c# linq-to-sql

我有以下代码,我需要在从数据库中检索结果后添加其他对象。关于我如何做到这一点的任何想法?

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

2 个答案:

答案 0 :(得分: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()的调用,它基本上说:“此时,我们不想在数据库中执行其余操作 - 将它们设置为本地。”

答案 1 :(得分: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;
相关问题