Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading