C# - LINQ Select 返回一个值,但变量仍然为 null

Ube*_*ffe 0 c# linq

private static readonly List<long> KnownPrimes = new List<long>() { 2, 3, 5, 7};
        
static void Main(string[] args)
{
    int numDivisors;
    string input = "";
    bool first = true;
    while (!int.TryParse(input, out numDivisors))
    {
        if(!first) Console.WriteLine("You must enter a number with no other characters.");
        Console.WriteLine("Find the least common multiple for numbers 1 through:");
        input = Console.ReadLine();
        first = false;
    }

    int index = -1;
    //make sure that there are enough primes in the list
    while (index == -1)
    {
                
        index = KnownPrimes.FindIndex(n => n > numDivisors);
        if(index == -1) AppendNextPrime();
     }
     // prep the list with 0s
     List<int> countPrimes = KnownPrimes.Select(n=>0) as List<int>;
Run Code Online (Sandbox Code Playgroud)

当我在 Rider 中调试最后一行时,它显示:

Enumerable.Select() returned: Count = 5       countPrimes: null
Run Code Online (Sandbox Code Playgroud)

从我读到的内容来看,LINQ 不应该返回 null,而且看起来也不是这样,但不知何故该变量仍然为 null。我显然在这里遗漏了一些东西,任何人都可以帮助我确定我做错了什么吗?

Kla*_*ter 5

as 运算符将返回 null,因为 Select 的结果不是List<int>而是IEnumerable<int>。将其替换为ToList从 IEnumerable 中创建一个列表:

List<int> countPrimes = KnownPrimes.Select(n=>0).ToList();