开发者

linq how to process each element?

开发者 https://www.devze.com 2023-01-07 21:50 出处:网络
I can never remember. How do i process each element in a string? I want to write stringblah.Split(\'/n\', Split(\'\\n\', StringSplitOpti开发者_StackOverflowons.RemoveEmptyEntries))

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

stringblah.Split('/n', Split('\n', StringSplitOpti开发者_StackOverflowons.RemoveEmptyEntries))
    .Each(s=>s.Trim());


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号