ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2022-09-08 15:30:09  阅读:156  来源: 互联网

标签:index convert ToList Items ICollection IEnumerable Cannot


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. – Anders Abel 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();

 

 

标签:index,convert,ToList,Items,ICollection,IEnumerable,Cannot
来源: https://www.cnblogs.com/chucklu/p/16669578.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有