Eric Smith
Eric Smith

Reputation: 2369

Returning proper type after using OrderBy()

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?

Upvotes: 8

Views: 6958

Answers (2)

Phillip
Phillip

Reputation: 175

It seems you're looking less for how to cast the result and more how to stuff it into a List<>. I was looking for a simple way to do the same thing and found the following solution:

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

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

Enumerable.ToList Method (MSDN)

Sorting a List<FileInfo> by creation date C#

Upvotes: 3

JaredPar
JaredPar

Reputation: 755161

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

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

Use of Method

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

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.

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

Upvotes: 5

Related Questions