在C#中将List <string>转换为List <int>的最快方法是什么,假设int.Parse适用于每个项目?

Kof*_*rfo 0 c# generics performance list

最快我的意思是什么是使用C#将List中的每个项目转换为int类型的最高效方法,假设int.Parse适用于每个项目?

Fem*_*ref 5

你不会绕过所有元素.使用LINQ:

var ints = strings.Select(s => int.Parse(s));
Run Code Online (Sandbox Code Playgroud)

这有额外的好处,它只会在你迭代它时转换,并且只有你要求的元素.

如果您确实需要列表,请使用该ToList方法.但是,您必须知道上面提到的性能奖励将无法使用.


Bro*_*ook 5

如果您真的想寻求最后一点性能,您可以尝试使用像这样的指针做一些事情,但就我个人而言,我会使用其他人提到的简单的 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
Run Code Online (Sandbox Code Playgroud)