3

I have this code :

 int[] g = new int[3] { 1, 2, 3 };
 g.ToList().ForEach(f=>Console.Write(f));

For each item in the array , I want to execute an Action....

int[] is already implementing Ienumerable.

I would like to execute an Action without "ToList()"

is there any other solution ( with one line of code) to do it ( without toList? i.e using its IEnumerable characteristics )

Royi Namir
  • 144,742
  • 138
  • 468
  • 792
  • 1
    possible duplicate of [Why is .ForEach() on IList and not on IEnumerable?](http://stackoverflow.com/questions/800151/why-is-foreach-on-ilistt-and-not-on-ienumerablet) – H H Mar 29 '12 at 12:46
  • 1
    Also possible duplicate of [LINQ equivalent of foreach for IEnumerable](http://stackoverflow.com/questions/200574/linq-equivalent-of-foreach-for-ienumerablet) – David Mar 29 '12 at 12:48

3 Answers3

10

You could use Array.ForEach instead:

Array.ForEach(g, f => Console.Write(f));

or even1:

Array.ForEach(g, Console.Write);

Personally I'd probably use a foreach loop instead though, for the reasons given by Eric Lippert...


1 If it compiles. I've given up trying to predict whether method group conversion will work in the context of generic type inference.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

ForEach() is a method in the List class, not the IEnumerable interface, so it would not be available to the array directly.

If you are hardcore about doing it one line of code and IEnumerable, you could use (or abuse) a method like Any() or All() and do your desired operation (in this case, printing) before returning an appropriate value that would cause the iteration to continue.

Or you could instead use Array.ForEach().

Omaha
  • 2,262
  • 15
  • 18
0

Inspired by Jon Skeet, here's a useful extension method that I wrote:

Client:

var jobs = new List<Job>() 
    { 
        new Job { Id = "XAML Developer" }, 
        new Job { Id = "Assassin" }, 
        new Job { Id = "Narco Trafficker" }
    };
jobs.Execute(ApplyFilter, j => j.Id);

public void ApplyFilter(string filterId) { }

Extension Method:

    public static void Execute<TSource, TKey>(this IEnumerable<TSource> source, Action<TKey> applyBehavior, Func<TSource, TKey> keySelector)
    {
        foreach (var item in source)
        {
            var target = keySelector(item);
            applyBehavior(target);
        }
    }
Scott Nimrod
  • 11,206
  • 11
  • 54
  • 118
  • Not sure that the key selector is worth it - after all, you can always use `jobs.Select(j => j.Id).Execute(ApplyFilter)` without it. – Jon Skeet Sep 11 '14 at 01:19