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>)
精彩评论