Convert '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 "Unable to implicitly convert the type" System.Collections.Generic.IEnumerable "to" System.Collections.ObjectModel.Collection. An explicit conversion exists (are you skipping listing?) "

imagePlaylist used as a list (I could use .ToList ()), but to match "CA1002 Do not expose shared lists." I want to convert a list to a collection.

-Thanks

+6
source share
2 answers

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

 public static Collection<MediaInfo> imagePlaylist imagePlaylist = new Collection<MediaInfo> ( imagePlaylist .Distinct(new API.MediaInfoComparer()) .ToList() ); 
+13
source

I created a small 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 perform the inline conversion and reuse the utility in your entire solution:

 imagePlaylist.Distinct(new API.MediaInfoComparer()).ToCollection(); 
+1
source

Source: https://habr.com/ru/post/904725/


All Articles