I'm supposted to make IQueryable handle particular cases where:
s => s.Trusting == searchTrusting
s => s.Trusted == searchTrusted
s => s.Trusting == searchTrusting and s => s.Trusted == searchTrusted
other cases
How am I supposted to make IQueryable request that would specify those cases. I never used IQueryable before.
My associate adviced me to use:
var specialCases = IQueryable.
IQueryable.
His comment was: this approach only partially fix problem try to combine IQueryable and separate if for each case.
How can I achieve combining IQueryable?
Before his comment ifs were in state of if, else if, else if, else To get the same result, my existing solution used:(it works)
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();
}
CodePudding user response:
From your LINQ query, I saw it is redundant with this statement
.Where(s => s.Type.Contains(searchType))
Hence, your IQueryable
query can be simplified as below:
...
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();
And lastly, materialize the query to execute the query via .ToList()
.