无法将带有 [] 的索引应用于 mvc 控制器中类型为 'System.Collections.Generic.ICollection<int> 的表达式

Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.ICollection<int> in mvc controller

public ActionResult addstandardpackage1(ICollection<int> SingleStay,ICollection<int> DOUBLESTAY,ICollection<int> TRIBLESTAY,ICollection<int> FAMILYSTAY,ICollection<int> EXTRABED)
{
    var s = SingleStay;
    for (int i = 0; i < SingleStay.Count; i++ )
    {
        var cal = SingleStay[i];
    }
    foreach (var key in SingleStay)
    {
        var value = key;
    }          

}

在 for 循环中,我收到错误消息,例如 Cannot apply indexing with [] to an expression of type 但我需要在 for 循环中,在 for each 中。因为基于 for 循环,我会将详细信息与其他集合列表绑定。请帮助我。

我在 var cal=Singlestay[i] 中遇到错误。

ICollection 不公开 indexer。您有三个选择:

  1. ICollection更改为IList
  2. 使用继承自 IEnumerableElementAt。但请注意 - 它效率不高。
  3. 评估传递给列表的集合 (ToList())

ICollection(及其公开的方法)在 msdn 上。

只需将其转换为数组即可:

var s = SingleStay.ToArray();

请注意,这会消耗额外的内存。

更好的方法是首先获取数组或任何其他支持索引器的集合形式。

另一种方法是使用索引变量来实现它:

 var s = SingleStay;
 int i = 0;
 foreach (var cal in s)
 {
    //do your stuff (Note: if you use 'continue;' here increment i before)
    i++;
 }

或者您可以使用

foreach (var item in Collection)
{
..................
}