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

use*_*560 15 c# model-view-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;
    }          

}
Run Code Online (Sandbox Code Playgroud)

在for循环中,我得到的错误就像无法将带有[]的索引应用于类型的表达式但是我需要for for循环,对于我得到的每一个.因为基于for循环我会将细节与其他集合列表绑定.请帮我.

我收到了错误var cal=Singlestay[i].

小智 18

ICollection没有曝光indexer.你有三个选择:

  1. 更改ICollectionIList
  2. 使用ElementAt继承自IEnumerable.但要注意 - 它可能效率不高.
  3. Evalute将集合传递给list(ToList())

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

  • 感谢ElementAt! (2认同)

Flo*_*ger 7

只需将其转换为数组:

var s = SingleStay.ToArray();
Run Code Online (Sandbox Code Playgroud)

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

更好的方法是首先获得一个Array或任何其他支持索引器的集合形式.

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

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