Apply function to all elements of collection through LINQ

C#.NetLinq

C# Problem Overview


I have recently started off with LINQ and its amazing. I was wondering if LINQ would allow me to apply a function - any function - to all the elements of a collection, without using foreach. Something like python lambda functions.

For example if I have a int list, Can I add a constant to every element using LINQ

If i have a DB table, can i set a field for all records using LINQ.

I am using C#

C# Solutions


Solution 1 - C#

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());

Solution 2 - C#

The idiomatic way to do this with LINQ is to process the collection and return a new collection mapped in the fashion you want. For example, to add a constant to every element, you'd want something like

var newNumbers = oldNumbers.Select(i => i + 8);

Doing this in a functional way instead of mutating the state of your existing collection frequently helps you separate distinct operations in a way that's both easier to read and easier for the compiler to reason about.

If you're in a situation where you actually want to apply an action to every element of a collection (an action with side effects that are unrelated to the actual contents of the collection) that's not really what LINQ is best suited for, although you could fake it with Select (or write your own IEnumerable extension method, as many people have.) It's probably best to stick with a foreach loop in that case.

Solution 3 - C#

You could also consider going parallel, especially if you don't care about the sequence and more about getting something done for each item:

SomeIEnumerable<T>.AsParallel().ForAll( Action<T> / Delegate / Lambda )

For example:

var numbers = new[] { 1, 2, 3, 4, 5 };
numbers.AsParallel().ForAll( Console.WriteLine );

HTH.

Solution 4 - C#

haha, man, I just asked this question a few hours ago (kind of)...try this:

example:

someIntList.ForEach(i=>i+5);

ForEach() is one of the built in .NET methods

This will modify the list, as opposed to returning a new one.

Solution 5 - C#

Or you can hack it up.

Items.All(p => { p.IsAwesome = true; return true; });

Solution 6 - C#

For collections that do not support ForEach you can use static ForEach method in Parallel class:

var options = new ParallelOptions() { MaxDegreeOfParallelism = 1 };
Parallel.ForEach(_your_collection_, options, x => x._Your_Method_());

Solution 7 - C#

You can try something like

var foo = (from fooItems in context.footable select fooItems.fooID + 1);

Returns a list of id's +1, you can do the same with using a function to whatever you have in the select clause.

Update: As suggested from Jon Skeet this is a better version of the snippet of code I just posted:

var foo = context.footable.Select(foo => foo.fooID + 1);

Solution 8 - C#

I found some way to perform in on dictionary contain my custom class methods

foreach (var item in this.Values.Where(p => p.IsActive == false))
            item.Refresh();

Where 'this' derived from : Dictionary<string, MyCustomClass>

class MyCustomClass 
{
   public void Refresh(){}
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMidhatView Question on Stackoverflow
Solution 1 - C#Jon SkeetView Answer on Stackoverflow
Solution 2 - C#mqpView Answer on Stackoverflow
Solution 3 - C#JaansView Answer on Stackoverflow
Solution 4 - C#andyView Answer on Stackoverflow
Solution 5 - C#Jack_2060View Answer on Stackoverflow
Solution 6 - C#zmechanicView Answer on Stackoverflow
Solution 7 - C#DrahcirView Answer on Stackoverflow
Solution 8 - C#user2500321View Answer on Stackoverflow