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

3

6

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

Gwen answered 30/12, 2011 at 5:15 Comment(2)
Does your collection need to expose Add and Remove to the public? Do you need to have random access via an index? If not, you could simply expose imagePlaylist as IEnumerable<MediaInfo> for a readonly sequence.Ariose
@anthonyPegram Those methods need to be exposed, using IEnumerable isnt an option in this caseGwen
F
13

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()
                    );
Ferricyanide answered 30/12, 2011 at 5:22 Comment(0)
C
2

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();
Chuipek answered 25/3, 2015 at 3:10 Comment(0)
O
1

Nowaday we finally have a cleaner and more readable way to do it with the collection expressions

public record MyItem(int Id, object data);

public class MyClass
{
    public Collection<MyItem> _myCollection;

    static Collection<MyItem> DummyMethodFillingCollection() => new();

    public void MyMethod()
    {
        _myCollection = DummyMethodFillingCollection();

        //here I want to modify the value of _myCollection and reassign it,
        //I can use the collection expression for the purpose
        _myCollection = [.. _myCollection.Distinct()];
    }
}
Ology answered 9/10 at 6:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.