简体   繁体   中英

Why is my code not iterating?

Why is my code not working as expected? The others (departmentName, employeeName and statusDescription) are working (shown below)

int countRow = 1;
//Query for account status
var query = from emp in db.EmployeeDetails
            join stat in db.Status on emp.statusId equals stat.statusId
            join dep in db.Department on emp.departmentId equals dep.departmentId
            where emp.employeeName == name
            select new { emp, stat, dep };  
foreach (var q in query)
{

    Console.WriteLine("{0,-3} | {1,-10} | {2,10}\t\t | {3,10}",
       countRow,
       q.dep.departmentName,
       q.emp.employeeName,
       q.stat.statusDescription);                
    Console.WriteLine("-----------");                
    countRow++;// <---------not adding: output keeps printing 1
}

It's working but my countRow is constantly having a value of 1

Right now, my output looks like this:

No.      Dep             Name      Status
1        Finance         John      Present
1        Education       Mary      Present
1        Recreational    Tom       Absent

What I'm looking for is this:

No.      Dep             Name      Status
1        Finance         John      Present
2        Education       Mary      Present
3        Recreational    Tom       Absent

UPDATE: It appears my "query" (in foreach var q in query) has a count value of 1. I suppose this is the cause of my issue. Does anyone know how I can fix this?

It seems like you're posting the results of multiple queries.

Your original query looks for a specific name ( emp.employeeName == name ) which yields, probably, a single result. The results you posted have multiple names in them, which means you're running this query more than once (maybe in an enclosing loop?). Each query initializes countRow to 1, so you get the same number every time. If you had multiple employees with the same name, you'd see numbers other than 1. As the comments suggest, try to find the enclosing loop and move the countRow = 1 initializer there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM