Using LINQ's FirstOrDefault to set a variable to the first non-blank value in a list

I came across an interesting use for LINQ that would prove to be useful when needing to set a variable based on a hierarchy. For example, when setting the SO Acknowledgement email address, my preference is to use the one on file for the selected contact, but if that’s empty go with the contact’s primary email address. Then, worst case, use the customer’s main email address. Here’s what the code would look like:

// 1st Choice: Contact's SO Ack Email, 2nd Choice: Contact's Primary Email, 3rd Choice: Customer Email
string SOAckEmail = new string[]{ContSOAck, ContEmail, CustEmail}.FirstOrDefault(s => !string.IsNullOrEmpty(s)) ?? "";

Unfortunately, this doesn’t appear to be selecting ContSOAck even though the string is populated. Any insights what I might have overlooked? It would really be handy if we could avoid all the IF statements.

Why not do something like this… it should pick ContSOAck first, but if blank, it would go to the next, and so on… Yea, this is kinda like an if/else but it’s simpler than your example above.

string SOAckEmail = ContSOAck ?? (ContEmail ?? (CustEmail ?? ""));

Thanks Tim. It’s definitely cleaner, but unfortunately I don’t think it’s working as expected yet.
For customer 100, I have three contacts. Contact #1 has a SOAckEmail specified, so when I pick them from the Attention drop-down and Update, I see that email in SOAckEmailAddress_c. Contact #2, however, has no SOAckEmail, but they do have a primary email address, so I would expect to see that email populate into SOAckEmailAddress_c, but instead I get a blank when selecting #2 and saving. Contact #3 has neither, so I would expect to see the customer’s default email populate into SOAckEmailAddress_c, but that is also blank when selecting #3 and saving.

SO your problem is that the string is not NULL… the double question mark is looking for a NULL… .instead your string is simply blank (equal to “”) which is different than null.
So… you could do something a little more complex like this… it is actually three if statements but in a single line form. The first part says "if the string is NOT (the exclamation sign) null or empty then use it… else use the next value if it is not empty, otherwise use the last value if it is not null… otherwise use “”.

String SOAckEmail = (!string.IsNullOrEmpty(ContSOAck)) ? ContSOAck : (!string.IsNullOrEmpty(ContEmail)) ? ContEmail : CustEmail ?? "";

(FYI… i really dislike compound in-line if statements, but, in this case, it is “ok”…)

Thanks Tim. That definitely did the trick. The LINQ query certainly looks like a cool idea, but this method is much more practical. Cheers!

Went back and looked… maybe THIS would work after all if you used the Where statement?..

string SOAckEmail = new string[]{ContSOAck, ContEmail, CustEmail}.Where(s => !string.IsNullOrEmpty(s)).FirstOrDefault() ?? "";