This is a noob question. So if I misstate the question, it’s because I am not fully understanding what is happening.
Issue
Compile error:
Cannot implicitly convert type ‘MyClass.Items’ to ‘System.Collections.Generic.List’
Context
I am in iterating a List through an IOrderedEnumerable, but I am unable to return the desired record because it is of typed List (since my whole app is passing List objects back and forth).
My input to the method is a List, but it seems to be implicitly cast to IEnumerable when I use the OrderBy option.
I have read everything I’ve found, but it all seems to boil down to:
// ToList is not available!
return SingleItemToCheck.ToList;
or
// same type conversion error
List<Items> ReturningList = SingleItemToCheck;
The Problem Code
public static List<Items> FindCheapestItem(List<Items> source)
{
// Now we pop only the first one.
// ISSUE: Sometimes the top entry on the list is bad,
// so we need to check it!
var BestItemCandidate = source.OrderBy(s => s.ItemDesirability);
bool ForgetThisOne = false;
foreach (var SingleItemToCheck in BestItemCandidate)
{
ForgetThisOne = false;
// ... test for ItemDesirability, truncated
if (Desirability < 0)
{
ForgetThisOne = true;
}
if (!ForgetThisOne)
{
// we are just returning the first desirable row
// because we are sorted on desirability
// and consuming code can only digest a single item.
return SingleItemToCheck; // !!! ARGH, compile error !!!
}
}
// means we looped through everything and found nothing of interest
return null;
}
SingleItemToCheckis a single item, it is not a list. It does not have aToList()method available. Simply create a list with that single item.Or if you’re only ever interested in the one item, change the return type of the method to simply
Itemsand omit the list entirely.Another way to write that, particularly if you’re only interested in the one item, is to simply refactor the inner loop logic to a function and then write a query
Otherwise, if you absolutely need a list, but only one item in it, consider
If no elements pass, this will be an empty list. You can then elect to return null, as your present code does, or return the empty list and let the callers deal with that instead of the null result.