Search code examples
c#.netgeneric-collections

How to Cast List<T> to my own Collection


I have implemented my own collection class for various reasons. How to avoid casting failure on ItemCollection resultCollection = (ItemCollection)list;? I'm inheriting from List<T> so shouldn't I be able to cast? Can I modify my BaseEntityCollection to become able to do this?

static class Program
{
    static void Main()
    {
        ItemCollection collection = new ItemCollection();
        Item item = new Item();
        item.ID = 1;
        item.Name = "John";
        collection.Add(item);
        List<Item> list = collection.FindAll(x => x.ID == 1 && x.Name == "John");

        ItemCollection resultCollection = (ItemCollection)list; // It's breaking here
    }
}


public class ItemCollection : BaseEntityCollection<Item>
{
}

public class Item : BaseEntity
{
    public int ID { get; set; }
    public string Name { get; set; }
}

public abstract class BaseEntityCollection<T> : List<T>, IEnumerable<T> where T : BaseEntity, new()
{
}

public abstract class BaseEntity
{
}

I know that I can implement FindAllseparately on my ItemCollection But I wanted to take advantage of all the methods available on List<T>.

Also I know that I can do list.ForEach(resultCollection.Add);. But that means iterating the collection all over again which I'd like to avoid.


Solution

  • ItemCollection resultCollection = new ItemCollection();
    resultCollection.AddRange(collection.Where(x => x.ID == 1 && x.Name == "John"));
    

    If by chance you don't have the AddRange extension method, make it.

    void AddRange<T>(this ItemCollection c, IEnumerable<T> items) => foreach(T i in items) c.Add(i);