开发者

Am I reinventing the wheel?

开发者 https://www.devze.com 2023-02-08 11:04 出处:网络
public开发者_StackOverflow社区 static void Apply<T>(this IList<T> source, Func<T, T> func)
public开发者_StackOverflow社区 static void Apply<T>(this IList<T> source, Func<T, T> func)
{
    for (int i = 0; i < source.Count; i++)
    {
        source[i] = func.Invoke(source[i]);
    }
}

Sample:

 List<string> fruits = new List<string> { "ApPel", "BANana", "oRANGE" };
 fruits.Apply((x) => x.ToUpper());

Result: APPLE BANANA ORANGE

  • Am I reinventing the wheel, or does this already exist?
  • Can Apply be written better?


fruits = fruits.Select(x => x.ToUpper()).ToList();


You're creating an in-place version of List<T>.ConvertAll:

fruits = fruits.ConvertAll(f => f.ToUpper());

ConvertAll is faster than Select(...).ToList(), because it never needs to resize a list.

EDIT: When you call .Select(...).ToList(), the ToList() call doesn't know how big the original list was. Therefore, it will create a small array, then repeatedly resize the array as it fills up.
By contrast, ConvertAll is part of the original list, and knows how big it is. It can therefore allocate an array of the correct size immediately, so it never needs to resize the array.

Your method is faster than either of them because you're modifying the list in-place. (You never create a new list at all)


The LINQ Select operator does this.

See the overload signatures:

Select<TSource, TResult>(IEnumerable<TSource>, Func<TSource, TResult>)
Select<TSource, TResult>(IEnumerable<TSource>, Func<TSource, Int32, TResult>)
0

精彩评论

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

关注公众号