为什么我的代码没有迭代?

时间:2015-04-16 09:27:14

标签: c# linq delayed-execution

为什么我的代码没有按预期工作?其他人(departmentName,employeeName和statusDescription)正在工作(如下所示)

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
}

它正在运作,但我的countRow的值一直是1

现在,我的输出如下:

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

我正在寻找的是:

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

更新: 它似乎是我的&#34;查询&#34; (在查询中的foreach var q中)的计数值为1.我想这是我的问题的原因。有谁知道我怎么解决这个问题?

1 个答案:

答案 0 :(得分:1)

好像你发布了多个查询的结果。

您的原始查询会查找特定名称(emp.employeeName == name),该名称可能会产生单个结果。您发布的结果中包含多个名称,这意味着您不止一次运行此查询(可能在封闭循环中?)。每个查询都会将countRow初始化为1,因此每次都会得到相同的数字。 如果您有多个具有相同名称的员工,您会看到除1之外的数字。如评论所示,尝试找到封闭循环并在那里移动countRow = 1初始值设定项。