Click here to Skip to main content
15,894,955 members
Articles / Programming Languages / C#
Tip/Trick

Replacing foreach loop with LINQ

Rate me:
Please Sign up or sign in to vote.
2.26/5 (9 votes)
5 Dec 2011CPOL 91.4K   8   20
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:
C#
var bestStudents = new List<Student>();
foreach (var s in students)
{
    if (s.Grade > 9)
    {
        bestStudents.Add(s);
    }
}


LINQ way:
C#
//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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer GE
Israel Israel
I am Software Developer at GE company for more than 2 years,

I created LINQTutorial.net since I didn't found any other good dedicate LINQ tutorial

Comments and Discussions

 
GeneralIn case some don't know, the result will not be 100% the sam... Pin
Riz Thon24-Oct-11 14:47
Riz Thon24-Oct-11 14:47 
In case some don't know, the result will not be 100% the same:
- in the 1st case you end up with a List<Student> which is created at once
- in the 2nd case you end up with a IEnumerable<Student> which will be evaluated once you iterate it.
As for me I don't like the SQL way of writing, I prefer students.Where(...).
Also if you do students.Where(s => s.Grade > 9).ToList() you'll end up with exactly the same as in the 1st case.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.