Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Select(x => ...Cast<x.GetType()>()) not work?

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.

like image 498
Tim Pohlmann Avatar asked Jul 08 '15 07:07

Tim Pohlmann


2 Answers

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:

  • Using 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.

  • Attempting to cast to 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.

like image 197
Jon Egerton Avatar answered Nov 03 '22 21:11

Jon Egerton


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());
like image 40
Sky Fang Avatar answered Nov 03 '22 21:11

Sky Fang