Linq检查值是否存在,否则设置默认值

时间:2013-06-20 18:59:59

标签: asp.net sql linq

嘿,我有以下疑问,即

    public int GetDefaultCurrencyForOrganization(string organizationId)
    {
        return (from a in _dataContext.allocations
                where a.organizationId.Equals(organizationId)
                select a.currencyId).SingleOrDefault();
    }

对于很多公司来说,这可能不会返回任何内容,而这是我想要设置值4来返回。只是想知道如何将其添加到上面?

2 个答案:

答案 0 :(得分:2)

我认为你正在寻找这样的东西:

public int GetDefaultCurrencyForOrganization(string organizationId)
{
    return (from a in _dataContext.allocations
            where a.organizationId.Equals(organizationId)
            select (int?)a.currencyId).SingleOrDefault() ?? 4;
}

你也可以这样做:

public int GetDefaultCurrencyForOrganization(string organizationId)
{
    var alloc = _dataContext.allocations
        .SingleOrDefault(a => a.organizationId.Equals(organizationId));
    return alloc != null ? alloc.currencyId : 4;
}

答案 1 :(得分:2)

尝试使用DefaultIfEmpty(4)而不是SingleOrDefault来指定值:

public int GetDefaultCurrencyForOrganization(string organizationId)
{
    return (from a in _dataContext.allocations
            where a.organizationId.Equals(organizationId)
            select a.currencyId).DefaultIfEmpty(4).Single();
}

http://msdn.microsoft.com/en-us/library/bb355419.aspx