![](/img/trans.png)
[英]Is it possible to split a value and add an if condition in a LINQ Query?
[英]How to add conditional condition to LINQ query based on a previously returned value
例如:
var sList = from ASL in aslist
where ASL.Description == as.ToString()
select ASL;
as = sList.FirstOrDefault();
var rList = from ARL in arlist
where ARL.Description == rDescription && ARL.Id == as.Id
select ARL;
現在,您看到了rList
查詢的最后一個條件(即&& ARL.Id == as.Id
)是基於從sList
查詢中檢索到的值。 我的問題是sList
為NULL
,出現錯誤。 我只想在sList
不為null的情況下包括最后一個條件(即&& ARL.Id == as.Id
)。
我可以使用如下所示的其他方式來做到這一點,但如果可能的話,我希望使用LINQ優雅地做到這一點:
if (as != null)
{
// include ARL.Id == as.Id condition in the query
}
else
{
// exclude ARL.Id == as.Id condition from the query
}
提前致謝!
&& (assetsensor == null || ARL.SensorID == assetsensor.ID)
根據您使用的查詢提供程序,如果您可以事先確定它不屬於該條件,我可能建議您根本不在LINQ查詢中包括該條件。 如果您使用的是LINQ to Objects,則可能不會有太大的區別,但是如果您使用的是LINQ to SQL或LINQ to Entities,那么在查詢中包括無關的條件可能會導致查詢提供程序生成不必要的SQL代碼如果提供者不了解您用來測試缺失值的代碼,則可能會影響性能的連接,甚至根本不起作用。
我會做類似的事情:
var sList = from ASL in assetsensorlist
where ASL.Description == assetSensor.ToString()
select ASL;
assetsensor = sList.FirstOrDefault();
var rList = from ARL in assetruleslist
where ARL.Description == ruleDescription
select ARL;
if (assentsensor != null)
{
// Fluent syntax is simpler for this purpose
rList = rList.Where(x => x.SensorID == assetsensor.ID);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.