无法隐式转换System.Collection.Generic.IEnumerable类型

时间:2010-03-08 13:47:13

标签: c# asp.net linq

我在Linq声明中收到此错误---

无法将类型'System.Collections.Generic.IEnumerable'隐式转换为'hcgames.ObjectClasses.ShoppingCart.ShoppingCartCartAddon'。存在显式转换(您是否错过了演员?)

来自此查询

        ShoppingCartItems items = Cart.GetAllItems();
        ShoppingCartCartAddons addons = Cart.GetAllAddons();

      var  stuff = from x in items
                    select new ShoppingCartItem()
                    {
                        ProductID = x.ProductID,
                        Quantity = x.Quantity,
                        Name = x.Name,
                        Price = x.Price,
                        Weight = x.Weight,
                        Addons =  (from y in addons
                                  where y.ShoppingCartItemID == x.ID
                                  select y)
                    };

我无法弄清楚如何正确施放。有什么建议吗?

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

我在黑暗中拍摄,因为我不知道ShoppingCartItem.Addons是什么类型,但从错误判断,我会说它希望该类型为hcgames.ObjectClasses.ShoppingCart.ShoppingCartCartAddon

您的LINQ查询正在变为IEnumerable<ShoppingCartCartAddon>。您可以将.FirstOrDefault()添加到LINQ查询中以查看是否清除了这些内容。

答案 1 :(得分:0)

考虑到您发布的代码,至少有一种方法可以解决它。更简单,更不优雅的是修改您的ShoppingCartItem.Addons签名,如下所示,因为您的ShoppingCartCartAddons集合没有任何其他功能:

namespace hcgames.ObjectClasses.ShoppingCart 
{ 
    [Serializable] 
    public class ShoppingCartItem 
    {
        public ShoppingCartItem(); 
        public ShoppingCartItem(DataRow dr); 
        public IEnumerable<ShoppingCartCartAddon> Addons { get; set; } 
        public string CartID { get; set; } 
        public int ID { get; set; } 
        public string Image { get; set; } 
        public string Name { get; set; } 
        public string Price { get; set; } 
        public long ProductID { get; set; } 
        public int Quantity { get; set; } 
        public decimal Weight { get; set; } 
    }
}

说明:您基本上是尝试从Collection<ShoppingCartCartAddon>初始化ShoppingCartCartAddons实现IEnumerable<ShoppingCartCartAddon>,因此编译器会成为奇迹。

否则,您可以为ShoppingCartCartAddons定义一个构造函数,该构造函数接受IEnumerable<ShoppingCartCartAddon>初始化。