Reputation: 1277
How can I simplify such statement:
var someList = new List<someType>();
if (String.IsNullOrEmpty(groupId))
{
someList = CTX.Values.Include(c => c.Customer).ToList();
}
else
{
someList = CTX.Values.Include(c => c.Customer).Where(c => c.GroupId== groupId).ToList();
}
The difference is only in .Where(c => c.GroupId== groupId)
. Is it possible to include the condition String.IsNullOrEmpty(groupId)
inside the query statement?
Upvotes: 0
Views: 333
Reputation: 33391
Maybe this?
someList = CTX.Values.Include(c => c.Customer)
.Where(c => String.IsNullOrEmpty(groupId)
|| c.GroupId== groupId)
.ToList();
EDITED BY PLB REQUEST :)
bool isGroupValid = String.IsNullOrEmpty(groupId);
someList = CTX.Values.Include(c => c.Customer)
.Where(c => isGroupValid
|| c.GroupId== groupId)
.ToList();
Upvotes: 3
Reputation: 17194
You can add:
.Where(c => String.IsNullOrEmpty(groupId))
That is:
CTX.Values.Include(c => c.Customer)
.Where(c => c.GroupId == groupId || c => String.IsNullOrEmpty(groupId))
.ToList();
Upvotes: 0
Reputation: 108880
You can construct the query in multiple steps. Simply add the Where
part only when groupId
is not empty.
The query will only be executed once you call ToList()
.
var values = CTX.Values.Include(c => c.Customer);
if(!String.IsNullOrEmpty(groupId))
values = values.Where(c => c.GroupId == groupId);
someList = values.ToList();
Upvotes: 7