Cannot convert from an IEnumerable to an ICollection

ICollection<T> inherits from IEnumerable<T> so to assign the result of

IEnumerable<T> Get(string pk)

to an ICollection<T> there are two ways.

// 1. You know that the referenced object implements `ICollection<T>`,
//    so you can use a cast
ICollection<T> c = (ICollection<T>)Get("pk");

// 2. The returned object can be any `IEnumerable<T>`, so you need to 
//    enumerate it and put it into something implementing `ICollection<T>`. 
//    The easiest is to use `ToList()`:
ICollection<T> c = Get("pk").ToList();

The second options is more flexible, but has a much larger performance impact. Another option is to store the result as an IEnumerable<T> unless you need the extra functionality added by the ICollection<T> interface.

Additional Performance Comment

The loop you have

for (var index = 0; index < Items.Count(); index++)

works on an IEnumerable<T> but it is inefficient; each call to Count() requires a complete enumeration of all elements. Either use a collection and the Count property (without the parenthesis) or convert it into a foreach loop:

foreach(var item in Items)

Leave a Comment