Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# is there a foreach oneliner available?

Tags:

syntax

c#

foreach

I just want to know if there is a foreach oneliner in C#, like the if oneliner (exp) ? then : else.

like image 678
Wowa Avatar asked Jan 25 '11 13:01

Wowa


4 Answers

If you're dealing with an array then you can use the built-in static ForEach method:

Array.ForEach(yourArray, x => Console.WriteLine(x));

If you're dealing with a List<T> then you can use the built-in ForEach instance method:

yourList.ForEach(x => Console.WriteLine(x));

There's nothing built-in that'll work against any arbitrary IEnumerable<T> sequence, but it's easy enough to roll your own extension method if you feel that you need it:

yourSequence.ForEach(x => Console.WriteLine(x));

// ...

public static class EnumerableExtensions
{
    public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
    {
        if (source == null) throw new ArgumentNullException("source");
        if (action == null) throw new ArgumentNullException("action");

        foreach (T item in source)
        {
            action(item);
        }
    }
}
like image 172
LukeH Avatar answered Nov 15 '22 18:11

LukeH


List.ForEach Method

like image 20
Denis Palnitsky Avatar answered Nov 15 '22 18:11

Denis Palnitsky


Imagine you have three variables and you want to set the same property of them all in only one go:

foreach (var item in new [] {labelA, labelB, labelC})
{
    item.Property= Value;
}

It is the equivalent of doing:

foreach (var item in new List<SomeType>(){labelA, labelB, labelC})
{
    item.Property= Value;
}
like image 6
sergiol Avatar answered Nov 15 '22 18:11

sergiol


foreach line-liners could be achieved with LINQ extension methods. For example:

instead of:

var result = new List<string>();
foreach (var item in someCollection)
{
    result.Add(item.Title);
}

you could:

var result = someCollection.Select(x => x.Title).ToList();
like image 5
Darin Dimitrov Avatar answered Nov 15 '22 20:11

Darin Dimitrov