DefaultIfEmpty not working

Why is the array still null after the DefaultIfEmpty request?

class Program
{
    static void Main(string[] args)
    {
        Program[] array = new Program[5];
        Program[] query = array.DefaultIfEmpty(new Program()).ToArray();
        foreach (var item in query)
        {
            Console.WriteLine(item.ToString());
        }
        Console.ReadKey();
    }
}
+3
source share
2 answers

Your array is not empty - it received 5 elements, each of which has a zero value.

Please note that it arrayitself is not null, nor is it query. But each element of them is null.

A truly empty array will have 0 elements:

using System;
using System.Linq;

class Program
{

    static void Main(string[] args)
    {
        Program[] array = new Program[0];
        Program[] query = array.DefaultIfEmpty(new Program()).ToArray();
        foreach (var item in query)
        {
            Console.WriteLine(item.ToString());
        }
        Console.ReadKey();
    }
}

Another alternative could be filtering null elements when copying an array:

Program[] query = array.Where(x => x != null)
                       .DefaultIfEmpty(new Program())
                       .ToArray();

EDIT: , DefaultIfEmpty? , . ; , . " ", :

Program[] query = array.Select(x => x ?? new Program())
                       .ToArray();

, Program ; Program , , :

Program defaultValue = new Program();
Program[] query = array.Select(x => x ?? defaultValue)
                       .ToArray();
+5

, :

var query = Array.ConvertAll(array, item => item ?? new Program());
+3

Source: https://habr.com/ru/post/1749786/


All Articles