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?
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 .
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).
No, LINQ iterators are not and will never be faster than foreach .
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.
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); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With