2011-05-14 67 views
0

当我输出这个代码时,当我只想要没有大括号的数字时,我得到{价格:1446}。有没有办法做到这一点?另外,一旦我得到价格值,我想将其转换为十进制。有没有办法做到这一点?LINQ删除大括号,铸造值

var flightPrice = (from f in XElement.Load(MapPath("flightdata.xml")).Elements("flight") 
          where (string)f.Element("flightnumber") == FlightNumber 
           && (string)f.Element("destinationairportsymbol") == Destination 
          select new { Price = (Int32)f.Element("price") } 
          ).SingleOrDefault(); 

lblPrice.Text = flightPrice.ToString(); 
+0

你能告诉我们你解析XML文件? – 2011-05-14 23:34:15

回答

1

您的select正在创建一个具有单一属性的匿名类型:Price。如果你想要的是实际价格(作为一个浮动),改变你的选择

// select new { Price = (Int32)f.Element("price") } 
select (float)(int)f.Element("price") 

但是,我们不建议您使用float应对金融东西像价格。数据类型decimal是此类值的首选类型。

select (decimal)f.Element("price") 
+0

是的,我想用小数点后两位小数。我该如何去使用它? – multiv123 2011-05-14 23:40:22

+0

@ multiv123,更新了答案,但它简单地转换为十进制而不是浮点型。 – 2011-05-14 23:45:15

+0

我需要将它作为十进制值存储,因为我需要使用它来计算税额。 – multiv123 2011-05-14 23:48:22

0

当你这样做会发生什么:

lblPrice.Text = flightPrice.Price.ToString(); 

你也可以这样做:

其中
// omited the first 3 lines of your linq statement... 
select (Int32)f.Element("price") 
).SingleOrDefault(); 

情况flightPriceint类型。

0

要么把select (Int32)f.Element("price")代替select new { Price = (Int32)f.Element("price") }

lblPrice.Text = flightPrice.Price.ToString();