views:

486

answers:

1

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?

+1  A: 

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;
}
JaredPar
While I had tried your first suggestion before already, I combined it with your second suggestion and it worked just fine. I'd have done it like that initially, I was just hoping for a more 'elegant' solution, I guess. Thanks!
Eric Smith