You don't need to create anonymous type:
decimal[] temp = dt.AsEnumerable()
.Select(r => r.Field<int>("Quantity")
* r.Field<decimal>("Breath")
* r.Field<decimal>("Length"))
.ToArray();
Question
Following Linq to datatable query gives me error Specific cast is not valid.
decimal[] temp = dt.AsEnumerable()
.Select(r => new
{
totLen = r.Field<decimal>("Quantity")
* (r.Field<decimal>("Breath")
* r.Field<decimal>("Length"))
})
.Cast<decimal>()
.ToArray();
Can any one suggest me why?
Solution
You don't need to create anonymous type:
decimal[] temp = dt.AsEnumerable()
.Select(r => r.Field<int>("Quantity")
* r.Field<decimal>("Breath")
* r.Field<decimal>("Length"))
.ToArray();
OTHER TIPS
You should be able to just return a decimal
straight from Select()
.
decimal[] temp = dt.AsEnumerable().Select(
r => r.Field<decimal>("Quantity") * (r.Field<decimal>("Breath") * r.Field<decimal>("Length")
)).ToArray();
You are trying to cast anonymous type to decimal, which of course will not work. Do not create anonymous type - simply select decimal value:
decimal[] temp = (from r in dt.AsEnumerable()
select r.Field<decimal>("Quantity") *
r.Field<decimal>("Breath") *
r.Field<decimal>("Length")).ToArray();
Same with Linq methods syntax:
decimal[] temp = dt.AsEnumerable()
.Select(r => r.Field<decimal>("Quantity") *
r.Field<decimal>("Breath") *
r.Field<decimal>("Length"))
.ToArray();
How to make your code work? Use Select
instead of Cast
:
.Select(x => x.totLen).ToArray();
But again, you don't need anonymous type to select single value.
Your projection (Select
) creates instances of anonymous type like this:
class SomeAnonymousClass
{
public totLen { get; set; }
}
...which instances can't be casted to decimal.