LINQ删除大括号,铸造值
问题描述:
当我输出这个代码时,当我只想要没有大括号的数字时,我得到{价格: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();
答
您的select
正在创建一个具有单一属性的匿名类型:Price。如果你想要的是实际价格(作为一个浮动),改变你的选择
// select new { Price = (Int32)f.Element("price") }
select (float)(int)f.Element("price")
但是,我们不建议您使用float
应对金融东西像价格。数据类型decimal
是此类值的首选类型。
select (decimal)f.Element("price")
答
当你这样做会发生什么:
lblPrice.Text = flightPrice.Price.ToString();
你也可以这样做:
其中// omited the first 3 lines of your linq statement...
select (Int32)f.Element("price")
).SingleOrDefault();
情况flightPrice
将int
类型。
答
要么把select (Int32)f.Element("price")
代替select new { Price = (Int32)f.Element("price") }
或
lblPrice.Text = flightPrice.Price.ToString();
你能告诉我们你解析XML文件? – 2011-05-14 23:34:15