2011-05-14 66 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();