Convert nested for each into single LINQ statement
-
jeudi 8 mars 2012 07:01
Hi,
I am new to LINQ to object, could anybody help in me converting below code into single LINQ statement.
foreach (DataRow objRow in objData.Rows)
{
foreach (var objComment in colComment) {
if(objComment.Code == objRow["Text"].ToString())
{
objComment.Code = Convert.ToString(objRow["IdField"]);
objComment.Desc = Convert.ToString(objRow["Text"]);break;
}
}
Thanks in Advance....
Toutes les réponses
-
jeudi 8 mars 2012 07:23
This is a case where I would recommend keeping your foreach loop - at least the outer one. LINQ is not intended for use when you're creating side effects (setting values), but rather for queries.
You could convert the inner loop into a query, and then loop over the results - but I doubt it would be more clear:
foreach (DataRow objRow in objData.Rows) { var commentsToEdit = colComment.Where(o => o.Code == objRow["Text"].ToString()); foreach(var objComment in colComment) { objComment.Code = Convert.ToString(objRow["IdField"]); objComment.Desc = Convert.ToString(objRow["Text"]); } }
While there are solutions using ToList().ForEach(...), I would not recommend them. For details as to why, see: http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx
Reed Copsey, Jr. - http://reedcopsey.com
If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".- Marqué comme réponse PrashantSahni vendredi 9 mars 2012 04:15
-
jeudi 8 mars 2012 09:04Thanks Reed Copsey

