Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to cast object of type 'System.Collections.Generic.List`1[System.Decimal]' to type 'System.IConvertible'

var itemlist = (from u in db.getitems
                select u).ToList();

var item= new EstimatesModel
             {
                 id = Convert.ToInt64(estimatelist.id),
                 expiry_date = estimatelist.expiry_date,
                 terms_conditions = estimatelist.terms_conditions,
                 rate = Convert.ToDecimal(itemlist.Select(m =>m.taxrate).ToList())

             };

return View(item);

Here in this query note that rate has more than 1 items coming from getitems where rate is Decimal type , so I converted it.

Then I am returning view on single entity item where only column rate is List.

But I am getting this error while debugging-

Unable to cast object of type 'System.Collections.Generic.List`1[System.Decimal]' to type 'System.IConvertible'.

I will use this like this in view page-

@for (int i = 0; i < Model.rate; i++)
{
    <ul>
        <li><a href="#">@i</a></li>
    </ul>
}
like image 565
user3163213 Avatar asked Apr 25 '14 08:04

user3163213


1 Answers

You are creating an IEnumerable<decimal> with this part of the line that assign the value to rate

  itemlist.Select(m =>m.taxrate)

Now you materialize the IEnumerable to a List<decimal> with

  itemlist.Select(m =>m.taxrate).ToList()

and pass this list to Convert.ToDecimal and, as far as I know, there is no overload of Convert.ToDecimal that accepts a List. Thus the error.

To resolve your problem we need to know what is the type of EstimatesModel.rate

If it is a simple decimal (not a list of decimals) then you need to tell us what value from the whole list should be used. The first, last, sum, average?

For example

rate = itemlist.Max(m =>m.taxrate);

or

rate = itemlist.First().taxRate;

EDIT Following your comment below, if you want to store in the EstimatesModel class a list of all the rates returned by the call to db.getitems then you need to define the field rate as a List<decimal>

public class EstimatesModel
{
    ....
    List<decimal> rate;
}

and then you could simply build your list with

rate = itemlist.Select(m =>m.taxrate).ToList()

no need to Convert.ToDecimal(... m.taxrate ...) being taxrate already a decimal

like image 53
Steve Avatar answered Sep 22 '22 19:09

Steve