对象初始化器中的Linq查询

时间:2013-10-04 10:21:27

标签: c# linq

我尝试初始化我正在实例化的List<OrderItem>的{​​{1}}字段,但我有以下代码。我的问题是Visual Studio不喜欢最内层的LINQ查询;具体而言,它抱怨Orderfromi.Element("OrderItems")

是不可能以这种方式初始化对象,还是我只是做错了什么?谢谢,康纳。

select

1 个答案:

答案 0 :(得分:3)

使用对象初始值设定项为IEnumerable<T>调用添加列表中的每个项目。但是,您无法直接提供IEnumerable<T>

http://msdn.microsoft.com/en-us/library/vstudio/bb384062.aspx

请考虑使用构造函数。

 OrderItems = new List<OrderItem>(
    from current in i.Element("OrderItems")
    select new OrderItem() {
        Product = new Product()
        {
            ID = new Guid(current.Element("ID").Value),
            UnitPrice = current.Element("UnitPrice").Value.To<decimal>()
        },
        Quantity = current.Element("Quantity").Value.To<int>(),
        TotalPrice = current.Element("TotalPrice").Value.To<decimal>()
    }
 )
相关问题