user3643560
user3643560

Reputation: 385

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;
    }          

}

In for Loop i am get the error like Cannot apply indexing with [] to an expression of type But i need in for loop , in for each i am getting . because based on for loop i will bind the details with other collection lists. Please Help me.

I am getting error in var cal=Singlestay[i].

Upvotes: 28

Views: 46874

Answers (3)

Yağmur Bilgin
Yağmur Bilgin

Reputation: 11

or you can use

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

Upvotes: 1

Florian Schmidinger
Florian Schmidinger

Reputation: 4692

Just convert it to an array:

var s = SingleStay.ToArray();

note that this will consume additional memory though.

Better way would be to get an Array or any other collection-form that supports indexer in the first place.

Yet another way would be to implement it with an index variable:

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

Upvotes: 15

user2160375
user2160375

Reputation:

ICollection doesn't expose indexer. You have three options:

  1. Change ICollection to IList
  2. Use ElementAt that is inherited from IEnumerable. But be aware - it could not be efficient.
  3. Evalute passed collection to list (ToList())

ICollection (and its exposed methods) on msdn.

Upvotes: 37

Related Questions