I have a DataTable that is populated from a database as follows:
SPName SName Row text
p_obj_prod1 dbo 1 A
p_obj_prod1 dbo 1 B
p_obj_prod1 dbo 1 C
p_obj_prod2 dbo 1 D
p_obj_prod2 dbo 1 E
p_rpt_prod3 dbo 1 F
p_rpt_prod3 dbo 1 G
p_rpt_prod3 dbo 1 H
And I have the following code that will process this data:
foreach (var row in procedureData.Tables[0].AsEnumerable()
.Select(dr => new { Schema = dr["SName"], Procedure = dr["SPName"] })
.Distinct())
{
//DO STUFF
foreach (string procedureText in procedureData.Tables[0].AsEnumerable()
.Where(dr => dr["SPName"] == row.Procedure).Select(dr => dr["text"]))
{
//DO MORE STUFF
}
//DO EVEN MORE STUFF
}
In this case I would expect the outer foreach loop to iterate 3 times, and it does. I would also expect that the inner foreach loop would iterate 3 times for the first outer loop iteration, 2 times for the second and 3 times for the third. However the inner loop only ever has one value (the first one in the sequence).
I’m not new to LINQ and have create far more complex queries than this, but this one really has me stumped on the reason why the inner loop doesn’t have all the expected results. I guess I have made a mistake in the second loop’s LINQ query, but it seems fine to me.
Can anyone shed some light on what might be the issue?
Thanks very much.
UPDATE
Just realised the mistake I was making and why the inner loop only had one value. It was because it was doing a reference comparison, not a value comparison on the ‘SPName’ column of the DataTable.
Changing the inner loop’s code to the following fixed the issue, however I will keep the GroupBy version as I prefer it!
foreach (string procedureText in procedureData.Tables[0].AsEnumerable()
.Where(dr => dr["SPName"].ToString() == row.Procedure.ToString())
.Select(dr => dr["text"]))
{
Why not just use a
GroupBy:Otherwise, I don’t see what’s wrong with your code. It works fine for me.