简体   繁体   中英

how to cast var to long array?

The following method returns array of long. But when i run it , get error :

specified cast is not valid.

public long[] GetLastMonthConsume(long metid)
{

   var lastconsume = (from itm in db.tblMonthConsumes
                            where itm.MetID_FK == metid && itm.MonthConsumeDate ==
                                (from itm2 in db.tblMonthConsumes
                                 where itm2.MeterID_FK == metid
                                 select itm2.MonthConsumeDate).Max()
                            select new
                            {
                                itm.MonthConsumeTotal,
                                itm.MonthConsumeTotalFuncHour
                            }).ToList();

    return lastconsume.Cast<long>().ToArray();
}

This error occurs in:

return lastconsume.Cast<long>().ToArray();

Data type of (MonthConsumeTotalFuncHour,MonthConsumeTotal) are long.

This cast is wrong? how to get output of query and cast to array of long???

You might need to return 2d array.

public long[][] GetLastMonthConsume(long metid)
{

   var lastconsume = (from itm in db.tblMonthConsumes
                            where itm.MetID_FK == metid && itm.MonthConsumeDate ==
                                (from itm2 in db.tblMonthConsumes
                                 where itm2.MeterID_FK == metid
                                 select itm2.MonthConsumeDate).Max()
                            select new
                            {
                               total = (itm.MonthConsumeTotal!= null && itm.MonthConsumeTotal.HasValue) ? itm.MonthConsumeTotal.Value : 0,
                               hour = (itm.MonthConsumeTotalFuncHour!= null && itm.MonthConsumeTotalFuncHour.HasValue) ? itm.MonthConsumeTotalFuncHour.Value : 0
                            }).ToList();

    return lastconsume.Select(t => new long[] {t.total , t.hour }).ToArray();
}

The lastConsume is a list of object of anonymous type as you used:

select new
{
   itm.MonthConsumeTotal,
   itm.MonthConsumeTotalFuncHour
}

Now you are trying to cast it into long which obviously not compatible. Hence, compiler showing error.

You will have to change method signature if you wish to return list of item with two long numbers.

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