如何使用LINQ </t>在.Select()内填充List <t>

时间:2011-04-25 20:41:56

标签: linq asp.net-mvc-2

我正在尝试使用以下LINQ查询从XML响应中填充IEnumerable<ResortSupplier>:如何在LINQ查询中填充/创建IList<PerPricing> PricingDetail?在当前场景中,IList<PerPricing>中只有一个项目(PerPricing),但它需要成为未来选项的IList并支持其他一些功能。我收到以下apporach的错误。

var resortPricing =
    xDoc.Elements("ResortPricingRS")
    .Elements("ResortPricing")
    .GroupBy(x => new
    {
        ID = x.Element(XName.Get("ResortId")).Value
    }
            )
    .Select(x => new ResortSupplier
    {
        SupplierCode = x.Key.ID,
        ResortProducts = x.Select(i => new Product
        {
            Code = i.Element("RoomCategory").Value,
            Description = i.Element("CategoryDesc").Value,
            Rating = (i.Elements("StarRatingCode").Any() ? i.Element("StarRatingCode").Value : ""),
            PricingDetail = { 
                            new PerPricing { 
                                    PricingType = "PerRoom",
                                    GroupNumber = 1 
                                    Price = decimal.Parse(i.Elements("TotalPrice").Any() ? i.Element("TotalPrice").Value : "0"),
                                    PricingError = (i.Elements("PricingError").Any() ? new Error { ErrorCode = i.Element("PricingError").Value } : null)
                                            } 
                            }
        }
                                ).ToList()
    }
            ).OrderBy(x => x.SupplierCode);

以下是我的目标:

[Serializable]
public class ResortSupplier
{
    public string SupplierCode { get; set; }
    public IList<Product> ResortProducts { get; set; }
}

[Serializable]
public class Product
{
    public string Code { get; set; }
    public string Description { get; set; }
    public string Rating { get; set; }
    public IList<PerPricing> PricingDetail { get; set; }
}

[Serializable]
public class PerPricing
{
    public string PricingType { get; set; }
    public int GroupNumber { get; set; }
    public decimal? Price { get; set; }
    public Error PricingError { get; set; }
}

1 个答案:

答案 0 :(得分:1)

像这样添加new []

PricingDetail = new [] { 
                        new PerPricing { 
                                PricingType = "PerRoom",
                                GroupNumber = 1 
                                Price = decimal.Parse(i.Elements("TotalPrice").Any() ? i.Element("TotalPrice").Value : "0"),
                                PricingError = (i.Elements("PricingError").Any() ? new Error { ErrorCode = i.Element("PricingError").Value } : null)
                                        } 
                        }
    }
                            ).ToList()