Cannot convert from an IEnumerable<T> to an ICollection<T>

Cannot convert from an IEnumerable<T> to an ICollection<T>

I have defined the following:

public ICollection<Item> Items { get; set; }

When I run this code:

Items = _item.Get("001");

I get the following message:

Error   3   
Cannot implicitly convert type 
'System.Collections.Generic.IEnumerable<Storage.Models.Item>' to 
'System.Collections.Generic.ICollection<Storage.Models.Item>'. 
An explicit conversion exists (are you missing a cast?)

Can someone explain what I am doing wrong. I am very confused about the difference between Enumerable, Collections and using the ToList()

Added information

Later in my code I have the following:

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

Would I be okay to define Items as an IEnumerable?

 

回答1

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)

 

评论

ICollection<T> can be manipulated (see the doc for details), while an IEnumerable<T> can only be enumerated. Jan 1, 2012 at 11:09
 
 

You cannot convert directly from IEnumerable<T> to ICollection<T>. You can use ToList method of IEnumerable<T> to convert it to ICollection<T>

someICollection = SomeIEnumerable.ToList();

 

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(26)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2021-09-08 OpenSSL errno 10054
2021-09-08 Why aren't telnet bots finishing the three-way handshake?
2021-09-08 Telnet shows blank screen on port 443 but TCP handshake not done 【openssl s_client -connect】
2021-09-08 You have a private key that corresponds to this certificate but CryptAcquireCertificatePrivateKey failed.
2021-09-08 劳动合同的必备条款有哪些?
2021-09-08 openssl pkcs12
2021-09-08 How to generate a self-signed SSL certificate using OpenSSL?
点击右上角即可分享
微信分享提示