Nemanja
Nemanja

Reputation: 73

Iteratin trought LINQ with index in collection

private void Right_Click(object sender, EventArgs e)
    {
        using (var ctx = new NORTHWNDEntities())
        {
            int txBoxId = int.Parse(Id.Text);


            var query = (from x in ctx.Employees where x.Employees1.Count >= txBoxId + 1 select x);
            List<Employee> emp = query.ToList();


            foreach (Employee c in emp)
            {
                Id.Text = c.EmployeeID.ToString();
                FirstName.Text = c.FirstName;
                LastName.Text = c.LastName;
                DateOfBirth.Text = c.BirthDate.Value.ToShortDateString();
            }
        }

    }

I want to go trought collection using index, any suggestion?

Upvotes: 1

Views: 49

Answers (1)

TVOHM
TVOHM

Reputation: 2742

emp is a List, you can simply iterate over every element in a normal for loop:

for(int index = 0; index < emp.Count; index++)
{
    var employee = emp[index];
    //...
}

Just seen your edit, you can access index in your query using method syntax instead of query syntax LINQ:

var query = ctx.Employees
    .Where((x, index) => x.Employees1.Count >= txBoxId + 1);

Upvotes: 1

Related Questions