Return the appropriate type after using OrderBy ()

I have a collection class that inherits from List<> . I created a function to sort the list using a specific property:

 public PlaylistCollection SortByName(IEnumerable<Playlist> playlists) { return (PlaylistCollection)playlists.OrderBy(p => p.Name); } 

When I try to use sorted results in my code, for example:

 artistSource.Playlists = (PlaylistCollection)new List<Playlist>(artistSource.Playlists.SortByName(artistSource.Playlists)); 

I get an error message:

 Unable to cast object of type 'System.Linq.OrderedEnumerable`2[...Playlist,System.String]' to type '...PlaylistCollection'." 

This is moderately frustrating given that VS told me that there was an explicit conversion, so I added the above listing.

How to properly drop from IEnumerable<> to my collection?

+7
generics casting c # linq
source share
2 answers

It is hard to understand what the correct answer is, without understanding more about the type of PlayListCollection. But assuming this is a standard type collection class that has a constructor with IEnumerable <T>, then the following code should do the trick.

Extension method

 public IEnumerable<Playlist> SortByName(IEnumerable<Playlist> playlists) { return playlists.OrderBy(p => p.Name); } 

Using method

 var temp = artistSource.Playlists.SortByName(artistSource.Playlists); artistSource.PlayList = new PlaystListCollection(temp); 

If not, provide additional information about the PlayListCollection, in particular the constructor and implemented interfaces, and we can help you solve your problem.

EDIT

If the above code does not work, you can use the following extension method to instantiate the PlaylistCollection class.

 public static PlaylistCollection ToPlaylistCollection(this IEnumerable<Playlist> enumerable) { var list = new PlaylistCollection(); foreach ( var item in enumerable ) { list.Add(item); } return list; } 
+5
source share

It seems you no longer look at how to distinguish the result and much more, how to write it to List<> . I searched for an easy way to do the same and found the following solution:

 artistSource.PlayList = playlists.OrderBy(p => p.Name).ToList<PlayList>(); 

The ToList extension ToList is available in .NET 3.5. The following links contain additional information:

Enumerable.ToList Method (MSDN)

Sort list <FileInfo> by C # creation date

+3
source share

All Articles