无法从IEnumerable <T>转换为ICollection <T>

Sam*_*tar 80 .net c#

我已经定义了以下内容:

public ICollection<Item> Items { get; set; }
Run Code Online (Sandbox Code Playgroud)

当我运行此代码时:

Items = _item.Get("001");
Run Code Online (Sandbox Code Playgroud)

我收到以下消息:

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?)
Run Code Online (Sandbox Code Playgroud)

有人可以解释我做错了什么.我对Enumerable,Collections和使用ToList()之间的区别感到很困惑

添加信息

稍后在我的代码中我有以下内容:

for (var index = 0; index < Items.Count(); index++) 
Run Code Online (Sandbox Code Playgroud)

我可以将Items定义为IEnumerable吗?

And*_*bel 97

ICollection<T>从此继承IEnumerable<T>以分配结果

IEnumerable<T> Get(string pk)
Run Code Online (Sandbox Code Playgroud)

一个ICollection<T>有两种方式.

// 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();
Run Code Online (Sandbox Code Playgroud)

第二种选择更灵活,但性能影响更大.另一种选择是将结果存储为IEnumerable<T>除非您需要ICollection<T>接口添加的额外功能.

附加表现评论

你有循环

for (var index = 0; index < Items.Count(); index++)
Run Code Online (Sandbox Code Playgroud)

工作IEnumerable<T>但是效率低下; 每次调用都Count()需要完整枚举所有元素.使用集合和Count属性(没有括号)或将其转换为foreach循环:

foreach(var item in Items)
Run Code Online (Sandbox Code Playgroud)

  • [ICollection <T>`](http://msdn.microsoft.com/en-us/library/92t2ye13.aspx)可以被操作(参见[doc](http://msdn.microsoft.com/en) -us/library/92t2ye13.aspx)有关详细信息),而`IEnumerable <T>`只能枚举. (6认同)

Har*_*san 28

你无法直接转换IEnumerable<T>ICollection<T>.您可以使用ToList方法IEnumerable<T>将其转换为ICollection<T>

someICollection = SomeIEnumerable.ToList();