Click here to Skip to main content
11,928,985 members (54,487 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


9 bookmarked

Replacing foreach loop with LINQ

, 5 Dec 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
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)

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


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


About the Author

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

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

You may also be interested in...

Comments and Discussions

GeneralReason for my vote of 5 I Liked it! Pin
onkuda0724-Oct-11 13:28
memberonkuda0724-Oct-11 13:28 

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.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.151126.1 | Last Updated 5 Dec 2011
Article Copyright 2011 by Delashmate
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid