Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 388
Eric Smith Avatar asked Apr 13 '09 22:04

Eric Smith


2 Answers

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;
}
like image 132
JaredPar Avatar answered Oct 13 '22 04:10

JaredPar


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#

like image 45
Phillip Avatar answered Oct 13 '22 03:10

Phillip