Cannot convert from an IEnumerable to an ICollection

前端 未结 3 1090
天命终不由人
天命终不由人 2020-12-09 00:25

I have defined the following:

public ICollection Items { get; set; }

When I run this code:

Items = _item.Get(\"         


        
3条回答
  •  情歌与酒
    2020-12-09 01:07

    Pending more information on the question:

    please provide more information on the type of item and the signature of Get

    Two things you can try are:

    • To cast the return value of _item.Get to (ICollection)
    • secondly to use _item.Get("001").ToArray() or _item.Get("001").ToList()

    Please note the second will incur a performance hit for the array copy. If the signature (return type) of Get is not an ICollection then the first will not work, if it is not IEnumerable then the second will not work.


    Following your clarification to question and in comments, I would personally declare the returning type of _item.Get("001") to ICollection. This means you won't have to do any casting or conversion (via ToList / ToArray) which would involve an unnecessary create/copy operation.

    // Leave this the same
    public ICollection Items { get; set; }
    
    // Change function signature here:
    // As you mention Item uses the same underlying type, just return an ICollection
    public ICollection Get(string value); 
    
    // Ideally here you want to call .Count on the collectoin, not .Count() on 
    // IEnumerable, as this will result in a new Enumerator being created 
    // per loop iteration
    for (var index = 0; index < Items.Count(); index++) 
    

    Best regards,

提交回复
热议问题