Unable to cast object of type 'System.Linq.OrderedEnumerable`2[***]' to type 'System.Collections.Generic.IEnumerable`1[***]'
Solution 1
You're trying to convert a collection of DirectoryToken
to a collection of Token
.
This is called a covariant conversion, and it's only supported in .Net 4.0 or later.
If you can't upgrade, you can call .Cast<Token>()
to create a new IEnumerable<T>
instance (actually an iterator) that casts each object to the desired type.
Under no circumstances do you need an explicit cast operation.
Solution 2
Right, not quite there yet.
List<String> PathValues = GetValues(settings.DirectoryDefinition.NameTokens.OrderBy(x => x.Index).Cast<Token>());
will work.
This is because although DirectoryToken
is a Token
, IEnumerable<DirectoryToken>
is NOT an IEnumerable<Token>
. You can't just cast directly do that.
Kobojunkie
I am a dedicated Developer at heart coding and pushing my way to becoming a master. Would really appreciate if you those who are not willing to share their knowledge, without question, avoid even posting a responses to questions asked. Some of us are here to learn from those who have know.
Updated on November 24, 2022Comments
-
Kobojunkie over 1 year
I have an object
DirectoryToken
that inherits from the classToken
. In my code I have aGetValues
method which takes a list of tokens, and puts together the value for each item in the list based on the information contained in the token object.//NameTokens is an object of type **List<DirectoryToken>** List<String> PathValues = GetValues((IEnumerable<Token>)settings.DirectoryDefinition.**NameTokens**.OrderBy(x => x.Index)); private List<String> GetReportValues(IEnumerable<Token> TokenList) { }
What I notice is when I run the code on one machine (Windows 7, .NET 3.5), it runs fine. However, when I move the built msi to another machine and try to run the same test, I get the following error message.
Unable to cast object of type 'System.Linq.OrderedEnumerable
2[DirectoryToken,System.Int32]' to type 'System.Collections.Generic.IEnumerable
1[Token]'.I don't think changing the code is the right way to attack this issue. Any suggestions what this problem could be from and maybe what version I can update my 3.5 to, to remedy this?