简体   繁体   中英

C# - LINQ Select returns a value but the variable is still null

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>;

When I debug that last line in Rider, it is showing:

Enumerable.Select() returned: Count = 5       countPrimes: null

From what I have read, LINQ shouldn't be able to return a null, and it doesn't appear to be, but somehow the variable is remaining null. I'm obviously missing something here, can anyone help me identify what I am doing wrong?

as operator will return null since the result of the Select ist no List<int> but an IEnumerable<int> . Replace it by ToList to make a List out of the IEnumerable:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM