Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable<>

Viewed 126985

Is there any specific reason why indexing is not allowed in IEnumerable.

I found a workaround for the problem I had, but just curious to know why it does not allow indexing.

Thanks,

10 Answers

You can use ToList to convert to a list. For example,

SomeItems.ToList()[1]

In my case I solved it by add .ToList() at the end of LINQ statement :

 public ActionResult Statistics(int programId )
        {
          
            int[] testids = { 51, 52, 54, 55, 56, 57, 60, 1125, 3161 };
            var stat = (from programs_tests in _context.programs_tests
                       join labTest in _context.LabTests
                       on programs_tests.testid equals labTest.TestId
                       where programs_tests.program_id == programId
                       && !testids.Contains(labTest.TestId)
                       select programs_tests).ToList();
        
           
            return View(stat);
         }

I had a column that did not allow nulls and I was inserting a null value.

You can use IEnumerable in conjunction with this:

public interface IWorksheets : IEnumerable
{
    IWorksheet this[int index] { get; }
    IWorksheet this[string name] { get; }
}

Then you can use foreach and indexing:

IWorksheet worksheet= excelWorkbook.Worksheets["Sheet1"]

foreach (IWorksheet worksheet in excelWorkbook.Worksheets)
{
Related