문제

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?

도움이 되었습니까?

해결책

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();

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top