user34537
user34537

Reputation:

linq how to process each element?

I can never remember. How do i process each element in a string? I want to write

stringblah.Split('/n', Split('\n', StringSplitOptions.RemoveEmptyEntries))
    .Each(s=>s.Trim());

Upvotes: 1

Views: 1170

Answers (2)

LukeH
LukeH

Reputation: 269498

Are you looking for Select?

var items = stringblah.Split(new[] {'\n'}, StringSplitOptions.RemoveEmptyEntries)
                      .Select(s => s.Trim());

// ...

foreach (var item in items)
{
    Console.WriteLine(item);
}

Upvotes: 5

drharris
drharris

Reputation: 11214

You can always make your own extension method:

public static class MyExtensions
{
    public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
    {
        foreach (T element in source) action(element);
    }
}

However, I would warn that most people would say you shouldn't do this. Using a traditional foreach loop is considered the better practice.

Upvotes: 1

Related Questions