Home > Net >  Does C# have a Linq method to run a function on the first element of a list, if it exists?
Does C# have a Linq method to run a function on the first element of a list, if it exists?

Time:12-01

I'm looking for something like the ForEach method but it only runs on one element.

// Do something with every element.
SomeList.ForEach(o => DoSomethingWith(o))

// Do something with just the first element, if any, or nothing at all for an empty list.
SomeLine.ForFirst(o => DoSomethingWith(o))

I'm trying to stick with a functional paradigm, and using the First, FirstOrOptional, FirstOrDefault, seem to end up involving a lot of Null checking or exception handling.

What is the Linq one-line way of doing this?

CodePudding user response:

Here's an approach which avoids assumptions about whether or not null elements are valid, and also avoids creating a list:

public static void ForFirst<T>(this IEnumerable<T> source, Action<T> action)
{
    using (var iterator = source.GetEnumerator())
    {
        if (iterator.MoveNext())
        {
            action(iterator.Current);
        }
    }
}

Or even, slightly weirdly:

public static void ForFirst<T>(this IEnumerable<T> source, Action<T> action)
{
    // The foreach loop will automatically dispose the iterator
    foreach (var item in source)
    {
        action(item);
        // Stop directly after the first element anyway
        break;
    }
}

(I'd probably not call it ForFirst myself, but that's a different matter.)

CodePudding user response:

collection.Take(1).ToList().ForEach(o => DoSomethingWith(o));

It performs all null and empty checks for you.

  • Related