Why is this an invalid LINQ cast?

100 Views Asked by At

I put raw data into a generic list. Then, I put data calculated from that raw data into another generic list, this one:

private List<ItemTotalsAcrossMonths> itemTotalsAcrossMonthsList;

The data (both raw and calculated) need to be displayed sorted, ordered by Total Purchases, so I want the data to be sorted that way. Since ordering a generic list returns another generic list, I first tried reassigning the sorted data into the original generic list:

itemTotalsAcrossMonthsList = (List<ItemTotalsAcrossMonths>)itemTotalsAcrossMonthsList.OrderByDescending(x => 
x.TotalPurchases13);

...but the road I'm on is apparently paved with good intentions, because this codeside bomb explodes in my face:

enter image description here

I tried putting the vals into a separate generic list of the same type:

private List<ItemTotalsAcrossMonths> itemTotalsAcrossMonthsList;
private List<ItemTotalsAcrossMonths> itemTotalsAcrossMonthsListSortedByTotalPurchasesDescending;
. . .
itemTotalsAcrossMonthsListSortedByTotalPurchasesDescending = (List<ItemTotalsAcrossMonths>)itemTotalsAcrossMonthsList.OrderByDescending(x => x.TotalPurchases13);

...but the results were eerily similar.

What do I need to do to sort the generic list?

3

There are 3 best solutions below

0
On BEST ANSWER

You're missing ToList() call.

LINQ methods return IEnumerable<T>, not List<T>, so you can't assume the implementation of interface is castable to List<T>.

You can call ToList() on LINQ query to get a list with the results.

0
On

OrderByDescending returns an OrderedEnumerable. Your type is a List. Simply call ToList() after your OrderByDescending to get back to your type.

3
On

The OrderByDescending method is a LINQ method. In general, LINQ works on IEnumerables, not Lists. You need to create a list from the IEnumerable using ToList() method:

itemTotalsAcrossMonthsList.OrderByDescending(x => x.TotalPurchases13).ToList();