pencilCake
pencilCake

Reputation: 53243

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

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.

Upvotes: 156

Views: 196826

Answers (7)

Ryan Naccarato
Ryan Naccarato

Reputation: 1181

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

Upvotes: 13

Tobias Knauss
Tobias Knauss

Reputation: 3509

Easy and without LINQ:

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

Upvotes: 4

user3450075
user3450075

Reputation: 161

The method OfType() will skip the null values:

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

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

Upvotes: 14

Paul Hiles
Paul Hiles

Reputation: 9778

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

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

Upvotes: 62

Steve Danner
Steve Danner

Reputation: 22158

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

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

Upvotes: 4

Mark Bell
Mark Bell

Reputation: 29745

The RemoveAll method should do the trick:

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

Upvotes: 29

Lance
Lance

Reputation: 5800

You'll probably want the following.

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

Upvotes: 294

Related Questions