Why does the following code produce an error?
var listOfList = new List<List<string>>();
var tmp = listOfList.Select(x => x.OrderBy(y => y).Cast<x.GetType()>());
Error:
Operator '<' cannot be applied to operands of type 'method group' and 'System.Type'
The code looks silly, because it's extremly simplified from my real example. I just wonder why it does not work exactly. It works if I replace x.getType()
with List<string>
, but I don't now the type of x at runtime.
For clarification: I don't necessary look for a solution. I want to know what exactly is wrong with my code.
The correct way to write the code is to use ToList
instead of Cast
as mentioned elsewhere.
However to answer the question "what exactly is wrong with my code?" there are two specific points to start with:
Cast<x.GetType()>()
:Generics are used with compile time type variables, so putting Cast<List<string>>()
would make more sense here - the x.GetType()
will only be resolved at run time. I guess the actually message you're getting is a result of the compiler getting muddled over this point.
List<string>
:Even if specific cast code syntax was reasonable, the actual cast would still fail. At this point you're attempting to cast an OrderedEnumerable<string>
to a List<string>
. This isn't a valid cast. The ToList()
resolves the otherwise un-resolved orderby statement to a list.
Why you need to do this? I guess you need this code
var listOfList = new List<List<string>>();
var tmp = listOfList.Select(x => x.OrderBy(y => y).ToList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With