开发者

What's the fastest way to convert List<string> to List<int> in C# assuming int.Parse will work for every item?

By fastest I mean what is the most performant means of converting each item in List to type int开发者_开发知识库 using C# assuming int.Parse will work for every item?


You won't get around iterating over all elements. Using LINQ:

var ints = strings.Select(s => int.Parse(s));

This has the added bonus it will only convert at the time you iterate over it, and only as much elements as you request.

If you really need a list, use the ToList method. However, you have to be aware that the performance bonus mentioned above won't be available then.


If you're really trying to eeke out the last bit of performance you could try doing someting with pointers like this, but personally I'd go with the simple linq implementation that others have mentioned.

unsafe static int ParseUnsafe(string value)
{
int result = 0;
fixed (char* v = value)
{
    char* str = v;
    while (*str != '\0')
    {
    result = 10 * result + (*str - 48);
    str++;
    }
}
return result;
}

var parsed = input.Select(i=>ParseUnsafe(i));//optionally .ToList() if you really need list


There is likely to be very little difference between any of the obvious ways to do this: therefore go for readability (one of the LINQ-style methods posted in other answers).

You may gain some performance for very large lists by initializing the output list to its required capacity, but it's unlikely you'd notice the difference, and readability will suffer:

List<string> input = ..
List<int> output = new List<int>(input.Count);
... Parse in a loop ...

The slight performance gain will come from the fact that the output list won't need to be repeatedly reallocated as it grows.


I don't know what the performance implications are, but there is a List<T>.ConvertAll<TOutput> method for converting the elements in the current List to another type, returning a list containing the converted elements.

List.ConvertAll Method


 var myListOfInts = myListString.Select(x => int.Parse(x)).ToList()

Side note: If you call ToList() on ICollection .NET framework automatically preallocates an
List of needed size, so it doesn't have to allocate new space for each new item added to the list.

Unfortunately LINQ Select doesn't return an ICollection (as Joe pointed out in comments).

From ILSpy:

// System.Linq.Enumerable
public static List<TSource> ToList<TSource>(this IEnumerable<TSource> source)
{
if (source == null)
{
    throw Error.ArgumentNull("source");
}
return new List<TSource>(source);
}

// System.Collections.Generic.List<T>
public List(IEnumerable<T> collection)
{
if (collection == null)
{
    ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
}
ICollection<T> collection2 = collection as ICollection<T>;
if (collection2 != null)
{
    int count = collection2.Count;
    this._items = new T[count];
    collection2.CopyTo(this._items, 0);
    this._size = count;
    return;
}
this._size = 0;
this._items = new T[4];
using (IEnumerator<T> enumerator = collection.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        this.Add(enumerator.Current);
    }
}
}

So, ToList() just calls List constructor and passes in an IEnumerable. The List constructor is smart enough that if it is an ICollection it uses most efficient way of filling a new instance of List

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜