SingleOrDefault,如何写出默认值?

时间:2013-07-26 13:41:07

标签: c# linq

我的以下查询

 var varUser = (from d in db.tblUsers where (d.ID == intID) select d).SingleOrDefault();
 return varUser.Forename + " " + varUser.Surname;

使用单一或默认时,如何输出默认值? 所以姓氏和姓氏是空的我想要“没有用户”而是

由于

4 个答案:

答案 0 :(得分:5)

检查用户是否为null(默认情况)并返回一些默认值(或抛出异常)

if (varUser == null)
    return "No User"; // default value or exception

return String.Format("{0} {1}", varUser.Forename, varUser.Surname);

提示:您可以将条件传递给SingleOrDefault方法:

db.tblUsers.SingleOrDefault(u => u.ID == intID)

如果您正在使用Entity Framework,甚至可以使用Find(如果在上下文跟踪的实体中找不到实体,则在内部调用SingleOrDefault)

db.tblUsers.Find(intID)

答案 1 :(得分:1)

return var varUser = db.tblUsers.SingleOrDefault(x=>x.id == intID) ?? "No User";

答案 2 :(得分:0)

试试这个

return varUser == null ? "No User" :
 string.Concat(varUser.Forename, " " , varUser.Surname);

答案 3 :(得分:0)

向用户类添加只读属性:

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

现在您可以使用这样的LINQ语句( DefaultIfEmpty 子句):

Dim varUser = (From d In db.tblUsers Where (d.ID == intID) Select d).DefaultIfEmpty(New User).SingleOrDefault()

Return varUser.FullName

抱歉我不熟悉C#因此VB代码。但是你明白了。