Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting 'System.Collections.Generic.IEnumerable<T>' to 'System.Collections.ObjectModel.Collection<T>'

I have a Collection, I'm trying to use the Distinct method to remove duplicates.

public static Collection<MediaInfo> imagePlaylist

imagePlaylist = imagePlaylist.Distinct(new API.MediaInfoComparer());

I get the error "Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Collections.ObjectModel.Collection'. An explicit conversion exists (are you missing a cast?)"

imagePlaylist used to be a List (i could use .ToList()), but to comply with "CA1002 Do not expose generic lists" I want to convert the List to a Collection.

-Thanks

like image 619
zaza Avatar asked Dec 30 '11 05:12

zaza


2 Answers

What you can do is, first convert the IEnumrable to generic list and then use this list to create a new Collection using the parametrized constructor of Collection class.

public static Collection<MediaInfo> imagePlaylist

imagePlaylist = new Collection<MediaInfo>
                    (
                       imagePlaylist
                      .Distinct(new API.MediaInfoComparer())
                      .ToList()
                    );
like image 57
Maheep Avatar answered Nov 12 '22 15:11

Maheep


I created a little extension method for this:

public static class CollectionUtils
{
    public static Collection<T> ToCollection<T>(this IEnumerable<T> data)
    {
        return new Collection<T>(data.ToList());
    }
}

So you can then do the conversion inline & reuse the utility throughout your solution:

imagePlaylist.Distinct(new API.MediaInfoComparer()).ToCollection();
like image 1
kiwiaddo Avatar answered Nov 12 '22 14:11

kiwiaddo