65.9K
CodeProject is changing. Read more.
Home

Replacing foreach loop with LINQ

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.26/5 (9 votes)

Oct 22, 2011

CPOL
viewsIcon

95907

Advantages of replacing a foreach loop with LINQ

In some cases LINQ can simplify iterative code, and in those cases, it's a good practice to switch iterative code into LINQ.

Regular foreach loop:
var bestStudents = new List<Student>();
foreach (var s in students)
{
    if (s.Grade > 9)
    {
        bestStudents.Add(s);
    }
}
LINQ way:
//LINQ query which generate the same result as the foreach loop above
var bestStudents = students.Where(s => s.Grade > 9).ToList();

Why does it look better with LINQ?

  1. Removing the if statement reduces the complexity (even if just a little)
  2. For me, declarative code is often more readable

Reference: LINQ Tutorial. Click here for more LINQ examples