简体   繁体   中英

Linq query “specific cast is not valid”

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 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 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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM