0

When I output this code, I get { Price: 1446 } when I only want the number without the braces. Is there a way to do this? Also, once I get the price value, I want to convert it to a decimal. Is there a way to do this?

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();
integral100x
  • 332
  • 6
  • 20
  • 47

3 Answers3

1

Your select is creating an anonymous type with a single property: Price. If all you want is the actual price (and as a float), change your select to

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

However, it is not recommended that you use a float to deal with something financial like a price. The decimal data type is the preferred type for such a value.

select (decimal)f.Element("price")
Anthony Pegram
  • 123,721
  • 27
  • 225
  • 246
  • Yes I would like to use decimal to two decimal places. How do I go about using it? – integral100x May 14 '11 at 23:40
  • @multiv123, updated the answer, but it is simply casting to decimal instead of float. – Anthony Pegram May 14 '11 at 23:45
  • i need to store it as a decimal value because i need to compute a tax value using it. – integral100x May 14 '11 at 23:48
  • By casting inside the `select` statement and using `Single`, your use of the `var` keyword means that the compiler will automatically infer the type of the variable to be `decimal`. You can also explicitly make it so by simply declaring `decimal flightPrice = ...` instead of `var flightPrice = `. – Anthony Pegram May 14 '11 at 23:55
  • Thanks. One more question, I'm trying to compute the tax as decimal tax = flightPrice * 0.35; but I'm getting a squiggly line error. How do I go about doing this? – integral100x May 15 '11 at 00:05
  • @multiv123, the compiler is inferring `0.35` as type `double`. To force the compiler to consider it a decimal, write it as `0.35m`. See this question for more on numeric suffixes: http://stackoverflow.com/questions/3271791/declaration-suffix-for-decimal-type/3271831#3271831 – Anthony Pegram May 15 '11 at 00:08
0

What happens when you do:

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

You can also do this:

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

in which case flightPrice will be of type int.

Kyle Trauberman
  • 25,414
  • 13
  • 85
  • 121
0

Either put select (Int32)f.Element("price") instead of select new { Price = (Int32)f.Element("price") }

or

lblPrice.Text = flightPrice.Price.ToString();
SirViver
  • 2,411
  • 15
  • 14