5

I have 1 to many relationship with the following tables - Person and Email. When using linq to sql and ASP.Net MVC, I'd like to show the first email or an empty string in my Person view using code like this:

<%= Html.Encode(Model.Emails.FirstOrDefault().EmailAddress) %>

In cases where there are no email rows, I receive a NullReferenceException. I can return null safe values from SQL by using a view or sproc, but I'd like to just stick with generic linq to sql objects bound to tables.

jlnorsworthy
  • 3,914
  • 28
  • 34

3 Answers3

8
Model.Emails.Select(x => x.EmailAddress).FirstOrDefault() ?? string.Empty
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
1
<%= Html.Encode((Model.Emails.FirstOrDefault() ?? new Email { EmailAddress = string.Empty }).EmailAddress) %>  

Would work, not super clean to read though.

Quintin Robinson
  • 81,193
  • 14
  • 123
  • 132
  • Thanks for your answer, the above is nearly the same but just a bit more concise – jlnorsworthy Feb 24 '10 at 23:06
  • This is better than others. 'cause Select methods is looping on all emails and its not good choose for performance. – cem Feb 25 '10 at 01:09
1

My vote for:

Model.Emails.Select(z => z.EmailAddress).DefaultIfEmpty("zzz").FirstOrDefault();

I thought that you could do it all inside the FirstOrDefault, but I was wrong-o! However, I also forgot that when you use DefaultIfEmpty you can just call First().

Model.Emails.Select(z => z.EmailAddress).DefaultIfEmpty("zzz").First();

Of course, replace ZZZ with just "" (not string.empty, that is unnecessary), but it is nice to see those records where the default is being chosen explicity when you are first writing it.

Andrew
  • 8,322
  • 2
  • 47
  • 70