Big Subjective Question: I often find myself using LINQ to filter a set of objects and then, after the query, doing an old fashion foreach to perform an action on each of the results. Is there a good way of combining these two tasks such that an action is performed on each object that matches the Where() predicate? Almost like passing an Action into the Select(). That probably would not compile, but what about passing in a Func that returns a bool, then you could nest that inside another query that could do something with the failures or successes. Has anyone done this in production code? Would this be considered bad practice? Any other thoughts?
It is slightly slowerLINQ syntax is typically less efficient than a foreach loop. It's good to be aware of any performance tradeoff that might occur when you use LINQ to improve the readability of your code. And if you'd like to measure the performance difference, you can use a tool like BenchmarkDotNet to do so.
No, LINQ iterators are not and will never be faster than foreach .
LINQ is a data querying API that provides querying capabilities to . NET languages with a syntax similar to a SQL. LINQ queries use C# collections to return data. LINQ in C# is used to work with data access from sources such as objects, data sets, SQL Server, and XML. LINQ stands for Language Integrated Query.
Readable code: LINQ makes the code more readable so other developers can easily understand and maintain it. Standardized way of querying multiple data sources: The same LINQ syntax can be used to query multiple data sources. Compile time safety of queries: It provides type checking of objects at compile time.
Many people have asked for a ForEach
method - and indeed it is handy (which is why we've got one in MoreLINQ). It's also potentially dangerous.
Most of LINQ firmly discourages side-effects. They're possible, but discouraged. That's why OrderBy etc return new collections rather than sorting existing ones.
Now consider ForEach
- it's an "action" rather than a function, in that it doesn't return anything. If it doesn't have any side-effects, it's absolutely pointless! So, it goes against part of the philosophy of LINQ - it's basically not approaching things in a functional style.
I'm not trying to make a case for or against, really - in practice, I think a useful thing to have, and I'm not surprised that it's in so many libraries etc. It's a very obvious pseudo-operator to add. Just think about what you're doing, and notice the fact that you're introducing side-effects. It's sort of a border between the functional style of LINQ and a more imperative style of coding.
List<T>
has a ForEach()
method that is designed for this.
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