Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
930 views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...