Reputation: 2587
My below query
var varUser = (from d in db.tblUsers where (d.ID == intID) select d).SingleOrDefault();
return varUser.Forename + " " + varUser.Surname;
When using single or default how do I output a default value? so forename and surname is empty i want to wirte "No User" instead
Thanks
Upvotes: 1
Views: 430
Reputation: 28427
Add a read-only property to your user class:
Public Class User
Public Property FirstName As String
Public Property LastName As String
Public ReadOnly Property FullName() As String
Get
If String.IsNullOrEmpty(FirstName) AndAlso String.IsNullOrEmpty(LastName) Then
Return "No Name"
Else
Return FirstName & " " & LastName
End If
End Get
End Property
End Class
Now you can use your LINQ statement like this (DefaultIfEmpty clause):
Dim varUser = (From d In db.tblUsers Where (d.ID == intID) Select d).DefaultIfEmpty(New User).SingleOrDefault()
Return varUser.FullName
Sorry am not proficient in C# hence the VB code. But you get the idea.
Upvotes: 0
Reputation: 4607
return var varUser = db.tblUsers.SingleOrDefault(x=>x.id == intID) ?? "No User";
Upvotes: 1
Reputation: 236278
Check if user is null
(default case) and return some default value (or throw exception)
if (varUser == null)
return "No User"; // default value or exception
return String.Format("{0} {1}", varUser.Forename, varUser.Surname);
HINT: You can pass condition to SingleOrDefault method:
db.tblUsers.SingleOrDefault(u => u.ID == intID)
Or even use Find if you are using Entity Framework (internally it calls SingleOrDefault if entity cannot be found in entities tracked by context)
db.tblUsers.Find(intID)
Upvotes: 5
Reputation: 15387
try this
return varUser == null ? "No User" :
string.Concat(varUser.Forename, " " , varUser.Surname);
Upvotes: 0