user1086396
user1086396

Reputation: 43

Conversion directly in LINQ query

I work with the Entity Framework and I have a LINQ query like this:

var foo = from ee in context.Table select new {id = ee.id, price = ee.price}.ToList();

where price is decimal (smallmoney in SqlServer). Now I bind it to a datagridview by mydgv.DataSource = foo; But first, I would like to convert all the decimals to strings in order to remove zeros from the value (ex. now it is 26.0000 and I want it to be 26.00). How can I do that? Something like:

bla.ForEach( x => x.price.ToString().Substring(0,3))

won't work.

Upvotes: 2

Views: 91

Answers (2)

Magnus
Magnus

Reputation: 46927

var q = foo.Select(x => new { id = x.id, price = x.price.ToString("N2") } );

But you can probably set a format-string on the column in the datagridview to "N2" and bind directly to your original datasource. Something like:

dgv.Columns[0].DefaultCellStyle.Format = "N2";

Upvotes: 2

svick
svick

Reputation: 244807

Not sure if EF supports it, but try

new { ee.id, price = ee.price.ToString("f2") }

Upvotes: 0

Related Questions