LINQ vs foreach in C#: Key Differences and When to Use Each
foreach is a simple loop used to iterate over collections directly, while LINQ provides a powerful query syntax to filter, transform, and select data from collections. foreach is straightforward and often faster, whereas LINQ offers more expressive and concise code for complex data operations.Quick Comparison
This table summarizes the main differences between LINQ and foreach in C#.
| Factor | LINQ | foreach |
|---|---|---|
| Syntax Style | Declarative query expressions | Imperative loop statements |
| Use Case | Filtering, projecting, and querying data | Simple iteration and processing of each item |
| Readability | Concise and expressive for complex queries | Clear and straightforward for simple loops |
| Performance | May have overhead due to deferred execution | Generally faster for direct iteration |
| Side Effects | Not recommended to have side effects inside queries | Commonly used for side effects like printing or modifying |
| Return Value | Returns new collections or values | Does not return a value, just executes code per item |
Key Differences
foreach is a basic loop that runs code on each item in a collection. It is easy to understand and is best when you just want to perform actions on each element without changing the data structure.
LINQ (Language Integrated Query) lets you write queries directly in C# to filter, sort, and transform collections. It uses a declarative style, meaning you describe what you want, not how to do it step-by-step.
While foreach executes immediately and is simple, LINQ queries often use deferred execution, meaning the query runs only when you use the results. This can add some overhead but allows for powerful chaining of operations. Also, LINQ is better for creating new collections or extracting data, while foreach is better for performing actions like printing or updating values.
Code Comparison
Here is how you use foreach to print all even numbers from a list.
using System; using System.Collections.Generic; class Program { static void Main() { List<int> numbers = new List<int> {1, 2, 3, 4, 5, 6}; foreach (int num in numbers) { if (num % 2 == 0) { Console.WriteLine(num); } } } }
LINQ Equivalent
This is the equivalent code using LINQ to select and print even numbers.
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { List<int> numbers = new List<int> {1, 2, 3, 4, 5, 6}; var evens = numbers.Where(num => num % 2 == 0); foreach (var num in evens) { Console.WriteLine(num); } } }
When to Use Which
Choose foreach when you need simple, direct iteration over a collection, especially if you want to perform side effects like printing or modifying items. It is clear and usually faster for straightforward tasks.
Choose LINQ when you want to write concise, readable code for filtering, sorting, or transforming data. It is ideal for complex queries and when you want to create new collections based on conditions.
In summary, use foreach for simple loops and side effects, and use LINQ for expressive data queries and transformations.
Key Takeaways
foreach is best for simple iteration and side effects.LINQ excels at querying and transforming collections declaratively.LINQ can be less performant due to deferred execution overhead.LINQ for readable, concise data queries.foreach for straightforward loops and immediate execution.