Chris Clark
Chris Clark

Reputation: 397

Setting a List to empty if it is null

I am trying to combine two lists, either one of these lists can be null. I understand that you should not be working with null lists, so I am trying to set them to an empty list before I combine them. The problem is, I can only seem to check if the second list is null when I am trying to concat, see below!

List<AccountAlert> xAccountEmails = new List<AccountAlert>();
List<AccountAlert> xAccountPhones = new List<AccountAlert>();
///Lots of things happen

//Below throws a compiler error cannot implicity convert IEnumerable to Generic.List
xAccountEmails = xAccountStuff.Where(x => x.prop == "prop").ToList() ?? Enumerable.Empty<AccountAlert>();
// Below throws the same compiler error
xAccountEmails = xAccountEmails ?? Enumerable.Empty<AccountAlert>();
//Below works!
xAccountPhones = xAccountStuff.Where(x => x.prop == "prop").ToList();
xAccountCombined = xAccountEmails.Concat(xAccountPhones ?? Enumerable.Empty<AccountAlert>()).ToList();

How would I test for and handle a null list if it is going to be the one concatenated onto?

Upvotes: 0

Views: 289

Answers (2)

Arturo Menchaca
Arturo Menchaca

Reputation: 15982

Firstly, check xAccountStuff for null, then if you want you can declare xAccountEmails and xAccountEmails lists when you do the Where calls.

Those lists never going to be null, maybe empty, but not null.

xAccountStuff = xAccountStuff ?? new List<AccountAlert>();

var xAccountEmails = xAccountStuff.Where(x => x.prop == "prop1").ToList();
var xAccountPhones = xAccountStuff.Where(x => x.prop == "prop2").ToList();

var xAccountCombined = xAccountEmails.Concat(xAccountPhones).ToList();

Upvotes: 1

D Stanley
D Stanley

Reputation: 152511

ToList will never return null. You do not need all of that null checking and converting to list. If you declare your variables as IEnumerable<AccountAlert> you can just do:

xAccountEmails = xAccountStuff.Where(x => x.prop == "prop");
xAccountPhones = xAccountStuff.Where(x => x.prop == "prop");

xAccountCombined = xAccountEmails.Concat(xAccountPhones);

Upvotes: 2

Related Questions