我應該讓 IQueryable 處理以下特殊情況:
s => s.Trusting == searchTrustings => s.Trusted == searchTrusteds => s.Trusting == searchTrusting and s => s.Trusted == searchTrustedother cases
我應該如何提出指定這些情況的 IQueryable 請求。我以前從未使用過 IQueryable。
我的同事建議我使用:
var specialCases = IQueryable.
IQueryable.
他的評論是:這種方法只能部分解決問題嘗試結合 IQueryable 并為每種情況分開 if。
如何實作組合 IQueryable?
在他發表評論之前,ifs 處于 if、else if、else if、else 狀態 為了獲得相同的結果,我使用了現有的解決方案:(它有效)
var domainTrustColl = _domainTrustRepository.GetDomainTrustItems().ToList().ConvertAll(new Converter<DomainTrustItem, DomainTrustModel>(DomainTrustModel.FromDomain));
domainTrustColl = domainTrustColl.Where(s => s.Trusting.Contains(searchTrusting)).Where(s => s.Trusted.Contains(searchTrusted)).Where(s => s.Type.Contains(searchType)).ToList();
if (!string.IsNullOrEmpty(searchTrusting))
{
domainTrustColl = domainTrustColl.Where(s => s.Trusting == searchTrusting).Where(s => s.Trusted.Contains(searchTrusted)).Where(s => s.Type.Contains(searchType)).ToList();
}
if (!string.IsNullOrEmpty(searchTrusted))
{
domainTrustColl = domainTrustColl.Where(s => s.Trusting.Contains(searchTrusting)).Where(s => s.Trusted == searchTrusted).Where(s => s.Type.Contains(searchType)).ToList();
}
if (!string.IsNullOrEmpty(searchTrusting) && !string.IsNullOrEmpty(searchTrusted))
{
domainTrustColl = domainTrustColl.Where(s => s.Trusting == searchTrusting).Where(s => s.Trusted == searchTrusted).Where(s => s.Type.Contains(searchType)).ToList();
}
uj5u.com熱心網友回復:
從您的 LINQ 查詢中,我看到這條陳述句是多余的
.Where(s => s.Type.Contains(searchType))
因此,您的IQueryable查詢可以簡化如下:
...
var query = domainTrustColl.Where(s => s.Type.Contains(searchType));
// Case - Both not selected
if (string.IsNullOrEmpty(searchTrusting) && string.IsNullOrEmpty(searchTrusted))
{
// Handle no select any case
}
// Third case - Both selected
else if (!string.IsNullOrEmpty(searchTrusting) && !string.IsNullOrEmpty(searchTrusted))
{
query = query.Where(s => s.Trusting == searchTrusting)
.Where(s => s.Trusted == searchTrusted);
}
// First case
else if (!string.IsNullOrEmpty(searchTrusting))
{
query = query.Where(s => s.Trusting == searchTrusting)
.Where(s => s.Trusted.Contains(searchTrusted));
}
// Second case
else if (!string.IsNullOrEmpty(searchTrusted))
{
query = query.Where(s => s.Trusting.Contains(searchTrusting))
.Where(s => s.Trusted == searchTrusted);
}
domainTrustColl = query.ToList();
最后,具體化查詢以通過.ToList().
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/455881.html
