I have a collection class that inherits from List<>. I’ve set up a function to sort the list by a certain property like so:
public PlaylistCollection SortByName(IEnumerable<Playlist> playlists) { return (PlaylistCollection)playlists.OrderBy(p => p.Name); }
When I try to use the sorted results in my code like this:
artistSource.Playlists = (PlaylistCollection)new List<Playlist>(artistSource.Playlists.SortByName(artistSource.Playlists));
I get the error:
Unable to cast object of type 'System.Linq.OrderedEnumerable`2[...Playlist,System.String]' to type '...PlaylistCollection'.'
This is moderately frustrating considering VS told me that an explicit conversion exists, so I added the above cast.
How do I properly cast from IEnumerable<> to my collection?
It’s hard to know what the right answer is without understanding more about the type PlayListCollection. But assuming it’s a standard style collection class which has a constructor taking an IEnumerable<T>, then the following code should do the trick.
Extension Method
Use of Method
If not, please post more information about PlayListCollection, in particular the constructor and implemented interfaces, and we should be able to help you out with your problem.
EDIT
If the above code does not work you can use the following extension method to create an instance of the PlaylistCollection class.