1

LINQ 的更多麻烦。只是希望有人可以帮忙。

这是我正在使用的结构;

<root>
   <Level1>
     <Level2>
       <Level3>
         <Car>
           <Price PaymentType="Cash">200</Price>
           <Price PaymentType="Credit">500</Price>
         </Car>
       </Level3>
     </Level2>
   </Level1>
</root>

我正在尝试创建两个 Let 变量来执行此操作;

Let priceCash = ??? // should return 200
Let priceCredit = ??? // should return 500

更复杂的是,并非所有汽车都有信用价格。对于这些我想返回-1。

这是我想出的屠杀代码;

// get all Price elements
let PriceList = CarList.Elements("Price") 

// try to get the first Price element where PaymentType==Cash
let priceCash = PriceList.Where(c => PriceList.Attributes("PaymentType").First().Value == "Cash")

// try to get the first Price element where PaymentType==Credit
let priceCredit = PriceList.Where(c => PriceList.Attributes("PaymentType").First().Value == "Credit")

有没有更好的方法来做到这一点?它似乎有效,但后来我在这里遇到了麻烦;

select new MyObj
{
    Price1 = priceCash == null ? -1 : priceCash.ElementAt(0).Value,
    Price2 = priceCredit == null ? -1 : priceCredit.ElementAt(0).Value,
}).ToList<MyObj>();

找不到元素时,ElementAt(0) 会导致异常。

干杯

4

2 回答 2

1

以下应该更健壮:

// try to get the first Price element where PaymentType==Cash
let priceCash = PriceList.FirstOrDefault(c => ((string)c.Attribute("PaymentType")) == "Cash")

// try to get the first Price element where PaymentType==Credit
let priceCredit = PriceList.FirstOrDefault(c => ((string)c.Attribute("PaymentType")) == "Credit")

select new MyObj
{
    Price1 = priceCash == null ? -1 : (int)priceCash,
    Price2 = priceCredit == null ? -1 : (int)priceCredit
}).ToList<MyObj>();
于 2013-09-19T14:00:31.103 回答
1

首先,使用Attribute方法,而不是Attributes().First链和(string)XAttribute转换而不是XAttribute.Value属性:

// get all Price elements
let PriceList = CarList.Elements("Price") 

// try to get the first Price element where PaymentType==Cash
let priceCash = PriceList.Where(c => (string)c.Attribute("PaymentType") == "Cash")

// try to get the first Price element where PaymentType==Credit
let priceCredit = PriceList.Where(c => (string)c.Attribute("PaymentType") == "Credit")

更重要的是,当元素不存在时DefaultIfEmpty用于获取:-1

select new MyObj
{
    Price1 = priceCash.Select(x => (int)x).DefaultIfEmpty(-1).First(),
    Price2 = priceCredit.Select(x => (int)x).DefaultIfEmpty(-1).First()
}).ToList<MyObj>();
于 2013-09-19T14:45:41.103 回答