How to remove null value from Lambda expression or Array
-
Here is my code: //Line below shows an email msg obj with To segment being an array (could have null to x number of receipients/emails): emailMessage.EmailParamHeaders.To //Below is creation of mail message obj: MailMessage m = new MailMessage(); //Line blow is adding each To email address to the "m" object emailMessage.EmailParamHeaders.To.ToArray().ToList().ForEach(x => m.To.Add(x)); How can I only add the elements of the array "To" where value is not null? Thank you in advance.
-
Here is my code: //Line below shows an email msg obj with To segment being an array (could have null to x number of receipients/emails): emailMessage.EmailParamHeaders.To //Below is creation of mail message obj: MailMessage m = new MailMessage(); //Line blow is adding each To email address to the "m" object emailMessage.EmailParamHeaders.To.ToArray().ToList().ForEach(x => m.To.Add(x)); How can I only add the elements of the array "To" where value is not null? Thank you in advance.
try this
emailMessage.EmailParamHeaders.To.ToArray().ToList().ForEach(x => {if(m != null) m.To.Add(x);});
-
try this
emailMessage.EmailParamHeaders.To.ToArray().ToList().ForEach(x => {if(m != null) m.To.Add(x);});
Thank you so much for the answer, that worked with minor change: emailMessage.EmailParamHeaders.To.ToArray().ToList().ForEach(x => { if (x != null) m.To.Add(x); });
-
Thank you so much for the answer, that worked with minor change: emailMessage.EmailParamHeaders.To.ToArray().ToList().ForEach(x => { if (x != null) m.To.Add(x); });
Why are you converting to array, and then to a list? Also, if your email message supports
AddRange
, an alternative is to try the following?var addresses = (from p in emailMessage.EmailParamHeaders.To
where p != null
select p).ToList();
if (addresses != null && addresses.Count>0)
m.To.AddRange(addresses);Depending what's going on inside the
Add
method, you can often find that anAddRange
works more efficiently.*pre-emptive celebratory nipple tassle jiggle* - Sean Ewington
"Mind bleach! Send me mind bleach!" - Nagy Vilmos
CodeStash - Online Snippet Management | My blog | MoXAML PowerToys | Mole 2010 - debugging made easier