簡體   English   中英

轉換列表最快的方法是什么 <string> 列出 <int> 在C#中假設int.Parse將適用於每個項目?

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

通過最快我的意思是在列表使用C#假設int.Parse會為每一個項目工作INT鍵入將每個項目的最高效的手段?

您將無法遍歷所有元素。 使用LINQ:

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

這具有額外的好處,它只會在您對其進行迭代時進行轉換,並且只會根據您的請求進行轉換。

如果確實需要列表,請使用ToList方法。 但是,您必須注意,上面提到的性能獎金將不可用。

如果您真的想獲取最后的性能,則可以嘗試使用類似這樣的指針進行操作,但就我個人而言,我會使用其他人提到的簡單linq實現。

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

實現此目的的任何顯而易見的方法之間幾乎沒有什么區別:因此,為了提高可讀性(其他答案中發布的LINQ風格方法之一)。

通過將輸出列表初始化為所需的容量,您可能會獲得非常大的列表性能,但是您不太可能會注意到其中的區別,並且可讀性會受到影響:

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

性能略有提高的原因是,隨着輸出列表的增加,不需要重復重新分配輸出列表。

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

旁注:如果在ICollection .NET Framework上調用ToList(),則會自動預分配一個
所需大小的列表,因此不必為添加到列表中的每個新項目分配新空間。

不幸的是,LINQ Select不返回ICollection(如Joe在評論中指出的那樣)。

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

因此,ToList()僅調用List構造函數並傳遞IEnumerable。 List構造函數足夠聰明,如果它是一個ICollection,則使用最有效的方式填充List的新實例

我不知道對性能的影響,但是有一個List<T>.ConvertAll<TOutput>方法,用於將當前List中的元素轉換為另一種類型,並返回包含轉換后元素的列表。

List.ConvertAll方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM