在SQL中可以运行ISNULL(null,''),如何在linq查询中执行此操作?
我在此查询中加入:
var hht = from x in db.HandheldAssets
join a in db.HandheldDevInfos on x.AssetID equals a.DevName into DevInfo
from aa in DevInfo.DefaultIfEmpty()
select new
{
AssetID = x.AssetID,
Status = xx.Online
};
但是我有一个列的位类型不可为空(xx.online),如果它为null,如何将其设置为false?
最佳答案
由于aa
是可能为空的集合/对象,因此您可以检查aa == null
吗?
(aa
/xx
可以互换(问题中的错字);最初的问题是关于xx
的,但仅定义了aa
)
IE。
select new {
AssetID = x.AssetID,
Status = aa == null ? (bool?)null : aa.Online; // a Nullable<bool>
}
或者,如果您希望默认值为
false
(而不是null
):select new {
AssetID = x.AssetID,
Status = aa == null ? false : aa.Online;
}
更新;为了应对下降的投票,我进行了更多调查……事实是,这是正确的方法!这是罗斯文的一个例子:
using(var ctx = new DataClasses1DataContext())
{
ctx.Log = Console.Out;
var qry = from boss in ctx.Employees
join grunt in ctx.Employees
on boss.EmployeeID equals grunt.ReportsTo into tree
from tmp in tree.DefaultIfEmpty()
select new
{
ID = boss.EmployeeID,
Name = tmp == null ? "" : tmp.FirstName
};
foreach(var row in qry)
{
Console.WriteLine("{0}: {1}", row.ID, row.Name);
}
}
这是TSQL-几乎是我们想要的(它不是
ISNULL
,但已经足够接近了):SELECT [t0].[EmployeeID] AS [ID],
(CASE
WHEN [t2].[test] IS NULL THEN CONVERT(NVarChar(10),@p0)
ELSE [t2].[FirstName]
END) AS [Name]
FROM [dbo].[Employees] AS [t0]
LEFT OUTER JOIN (
SELECT 1 AS [test], [t1].[FirstName], [t1].[ReportsTo]
FROM [dbo].[Employees] AS [t1]
) AS [t2] ON ([t0].[EmployeeID]) = [t2].[ReportsTo]
-- @p0: Input NVarChar (Size = 0; Prec = 0; Scale = 0) []
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.1
QED?
关于c# - 等价于LINQ中的SQL ISNULL?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/413084/