How to remove all the null elements inside a generic list in one go?

C#ListNullElement

C# Problem Overview


Is there a default method defined in .Net for C# to remove all the elements within a list which are null?

List<EmailParameterClass> parameterList = new List<EmailParameterClass>{param1, param2, param3...};

Let's say some of the parameters are null; I cannot know in advance and I want to remove them from my list so that it only contains parameters which are not null.

C# Solutions


Solution 1 - C#

You'll probably want the following.

List<EmailParameterClass> parameterList = new List<EmailParameterClass>{param1, param2, param3...};
parameterList.RemoveAll(item => item == null);

Solution 2 - C#

I do not know of any in-built method, but you could just use linq:

parameterList = parameterList.Where(x => x != null).ToList();

Solution 3 - C#

The RemoveAll method should do the trick:

parameterList.RemoveAll(delegate (object o) { return o == null; });

Solution 4 - C#

The method OfType() will skip the null values:

List<EmailParameterClass> parameterList =
    new List<EmailParameterClass>{param1, param2, param3...};

IList<EmailParameterClass> parameterList_notnull = 
    parameterList.OfType<EmailParameterClass>();

Solution 5 - C#

There is another simple and elegant option:

parameters.OfType<EmailParameterClass>();

This will remove all elements that are not of type EmailParameterClass which will obviously filter out any elements of type null.

Here's a test:

class Program
{
    class Test { }

    static void Main(string[] args)
    {
        var list = new List<Test>();
        list.Add(null);
        Console.WriteLine(list.OfType<Test>().Count());// 0
        list.Add(new Test());
        Console.WriteLine(list.OfType<Test>().Count());// 1
        Test test = null;
        list.Add(test);
        Console.WriteLine(list.OfType<Test>().Count());// 1

        Console.ReadKey();
    }
}

Solution 6 - C#

List<EmailParameterClass> parameterList = new List<EmailParameterClass>{param1, param2, param3...};

parameterList = parameterList.Where(param => param != null).ToList();

Solution 7 - C#

Easy and without LINQ:

while (parameterList.Remove(null)) {};

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpencilCakeView Question on Stackoverflow
Solution 1 - C#LanceView Answer on Stackoverflow
Solution 2 - C#Paul HilesView Answer on Stackoverflow
Solution 3 - C#Mark BellView Answer on Stackoverflow
Solution 4 - C#user3450075View Answer on Stackoverflow
Solution 5 - C#Ryan NaccaratoView Answer on Stackoverflow
Solution 6 - C#Steve DannerView Answer on Stackoverflow
Solution 7 - C#Tobias KnaussView Answer on Stackoverflow