Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ equivalent of foreach for IEnumerable<T>

I'd like to do the equivalent of the following in LINQ, but I can't figure out how:

IEnumerable<Item> items = GetItems(); items.ForEach(i => i.DoStuff()); 

What is the real syntax?

like image 663
tags2k Avatar asked Oct 14 '08 09:10

tags2k


People also ask

Can I use foreach in IEnumerable C#?

In C#, it is not strictly necessary for a collection class to implement IEnumerable and IEnumerator in order to be compatible with foreach . As long as the class has the required GetEnumerator , MoveNext , Reset , and Current members, it will work with foreach .

How do you foreach in LINQ?

Convert a foreach loop to LINQ refactoringPlace your cursor in the foreach keyword. Press Ctrl+. to trigger the Quick Actions and Refactorings menu. Select Convert to LINQ or Convert to Linq (call form).

Is LINQ faster than foreach C#?

No, LINQ iterators are not and will never be faster than foreach .

What can I use instead of foreach C#?

Why: You prefer to use LINQ syntax rather than a foreach loop. LINQ makes a query into a first-class language construct in C#. LINQ can reduce the amount of code in a file, make the code easier to read, and allow different data sources to have similar query expression patterns.


1 Answers

There is no ForEach extension for IEnumerable; only for List<T>. So you could do

items.ToList().ForEach(i => i.DoStuff()); 

Alternatively, write your own ForEach extension method:

public static void ForEach<T>(this IEnumerable<T> enumeration, Action<T> action) {     foreach(T item in enumeration)     {         action(item);     } } 
like image 79
Fredrik Kalseth Avatar answered Sep 18 '22 14:09

Fredrik Kalseth