Linq style For Each
Using the ToList() extension method is your best option:
someValues.ToList().ForEach(x => list.Add(x + 1));
There is no extension method in the BCL that implements ForEach directly.
Although there's no extension method in the BCL that does this, there is still an option in the System
namespace... if you add Reactive Extensions to your project:
using System.Reactive.Linq;
someValues.ToObservable().Subscribe(x => list.Add(x + 1));
This has the same end result as the above use of ToList
, but is (in theory) more efficient, because it streams the values directly to the delegate.
LINQ equivalent of foreach for IEnumerableT
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);
}
}
How to iterate over all elements in array(or list) with LINQ?
gameObjects.ToList().ForEach(x => {do Stuff with list});
Some reading on forEach in C# however. Could be interesting: https://blogs.msdn.microsoft.com/ericwhite/2009/04/08/why-i-dont-use-the-foreach-extension-method/
LINQ or foreach - style/readability and speed
I think All
would be clearer:
private bool AllItemsAreSatisfactoryV1(IEnumerable<Source> collection)
{
return collection.Select(f => SomeFancyLookup(f)).All(t => t.Satisfactory);
}
I think it's unlikely using linq here would cause a performance problem over a regular foreach loop, although it would be straightforward to change if it did.
How to use linq instead of foreach loop in c#
I've tried to write something like that
itemList = arrayIds.ForEach(x => getItem(x));
ForEach()
works on List<T>
:
arrayIds.ToList().ForEach(x => getItem(x));
But what you want is:
var itemList = arrayIds.Select(getItem).ToList();
Or if you only want to enumerate the items:
var items = arrayIds.Select(getItem);
Can all 'for' loops be replaced with a LINQ statement?
Sure. Heck, you can replace arithmetic with LINQ queries:
http://blogs.msdn.com/ericlippert/archive/2009/12/07/query-transformations-are-syntactic.aspx
But you shouldn't.
The purpose of a query expression is to represent a query operation. The purpose of a "for" loop is to iterate over a particular statement so as to have its side-effects executed multiple times. Those are frequently very different. I encourage replacing loops whose purpose is merely to query data with higher-level constructs that more clearly query the data. I strongly discourage replacing side-effect-generating code with query comprehensions, though doing so is possible.
Is it bad practice to use LINQ to loop over and perform actions rather than just select data?
List<T>
has a ForEach()
method that is designed for this.
Apply function to all elements of collection through LINQ
A common way to approach this is to add your own ForEach
generic method on IEnumerable<T>
. Here's the one we've got in MoreLINQ:
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
source.ThrowIfNull("source");
action.ThrowIfNull("action");
foreach (T element in source)
{
action(element);
}
}
(Where ThrowIfNull
is an extension method on any reference type, which does the obvious thing.)
It'll be interesting to see if this is part of .NET 4.0. It goes against the functional style of LINQ, but there's no doubt that a lot of people find it useful.
Once you've got that, you can write things like:
people.Where(person => person.Age < 21)
.ForEach(person => person.EjectFromBar());
Related Topics
Windows 7 Progress Bar in Taskbar in C#
How to Compile and Run C# Program Without Using Visual Studio
Why Do We Need the "Event" Keyword While Defining Events
Run the Current Application as Single Instance and Show the Previous Instance
Current Possibilities for Tracing Program Flow in C#
Convert List to Dictionary Using Linq and Not Worrying About Duplicates
Cannot Convert Lambda Expression to Type 'String' Because It Is Not a Delegate Type
.Net Core 3 Yields Different Floating Point Results from Version 2.2
How to Connect and Use a SQLite Database from C#
Iis Express Immediately Shutting-Down Running Site After Stopping Web Application
How to Validate Signature of Jwt from Jwks Without X5C
Cannot Resolve Scoped Service from Root Provider .Net Core 2
Rsa Encryption, Getting Bad Length
How to Find Reason of Failed Build Without Any Error or Warning