[英]LINQ Errors out on Any() if results NULL
我有一個LINQ查詢,在某些情況下,它不返回任何值。 因此,我正在使用Any()
進行檢查,以便可以相應地處理代碼。 但是當我使用Any()
或Count()
,出現以下錯誤:
{"Value cannot be null.\r\nParameter name: g"}
這是我正在使用的代碼:
var cQuery = (from a in gServiceContext.CreateQuery("contact")
where ((((EntityReference)a["accountid"]).Id.Equals(new Guid(p.AccountGuid))) &&
((a["firstname"].Equals(p.FirstName) && a["lastname"].Equals(p.LastName) && a["address1_stateorprovince"].Equals(p.State)) || (a["emailaddress1"].Equals(p.Email))))
select new
{
ContactId = !a.Contains("contactid") ? string.Empty : a["contactid"],
FirstName = !a.Contains("firstname") ? string.Empty : a["firstname"],
LastName = !a.Contains("lastname") ? string.Empty : a["lastname"],
State = !a.Contains("address1_stateorprovince") ? string.Empty : a["address1_stateorprovince"],
Email = !a.Contains("emailaddress1") ? string.Empty : a["emailaddress1"]
}).DefaultIfEmpty();
if (cQuery.ToList().Any())
{
// Do something if I get results
} else {
// Something else if no results
}
有什么想法我做錯了嗎? 似乎它應該為我工作。 在錯誤輸出的情況下。 它不會返回任何結果,所以我希望它跳過if
。 但是在其他情況下,將會有結果。 謝謝!
更新:
我知道代碼很丑陋。 抱歉。
看來問題在於:
where ((((EntityReference)a["accountid"]).Id.Equals(new Guid(p.AccountGuid)))
看起來在哪里獲得NULL。 我將如何處理,以免錯誤彈出?
參數名稱“ g”是new Guid(string g)
構造函數中的參數名稱。
因此,我懷疑您的根本原因實際上是在某些情況下P.AccountGuid
為空。
為什么不直接使用ToList函數呢?
var cQuery = (from a in gServiceContext.CreateQuery("contact")
where ((((EntityReference)a["accountid"]).Id.Equals(new Guid(p.AccountGuid))) &&
((a["firstname"].Equals(p.FirstName) && a["lastname"].Equals(p.LastName) && a["address1_stateorprovince"].Equals(p.State))
|| (a["emailaddress1"].Equals(p.Email))))
select new
{
ContactId = !a.Contains("contactid") ? string.Empty : a["contactid"],
FirstName = !a.Contains("firstname") ? string.Empty : a["firstname"],
LastName = !a.Contains("lastname") ? string.Empty : a["lastname"],
State = !a.Contains("address1_stateorprovince") ? string.Empty : a["address1_stateorprovince"],
Email = !a.Contains("emailaddress1") ? string.Empty : a["emailaddress1"]
}).ToList();
if (cQuery.Count > 0)
{
// Do something if I get results
}
else
{
// Something else if no results
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.