views:

85

answers:

4

Hi,

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

Lets say some of the paramters 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.

+11  A: 

You'll probably want the following.

List<EmailParameterClass> parameterList = new List<EmailParameterClass>{param1, param2, param3...};
parameterList.RemoveAll(item => item == null);
Lance May
Yep, this is the same as my answer but using the newer C#3 lambda syntax.
Mark B
@Mark: I saw the posted seconds and man it was close (32, 33, and 34). ;)
Lance May
Ha :) Well, fair play - your answer used neater syntax so +1
Mark B
Yeah... well your answer works even in older versions so +1! So there, ha! ;Þ
Lance May
+6  A: 

The RemoveAll method should do the trick:

parameterList.RemoveAll(delegate (object o) { return o == null; });
Mark B
A: 

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

parameterList = parameterList.Where(x => x != null).ToList();
Paul Hiles
+1  A: 
List<EmailParameterClass> parameterList = new List<EmailParameterClass>{param1, param2, param3...};

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