How to ignore blank elements in linq query
How to ignore blank elements in linq query
I have a linq query
var usersInDatabase =
from user in licenseUserTable
where user.FirstName == first_name &&
user.LastName == last_name
select user;
But if I get here and first_name o开发者_如何学JAVAr last_name is blank then I want to still evaluate the other data item.
var usersInDatabase =
from user in licenseUserTable
where
(user.FirstName == first_name || first_name == string.Empty) &&
(user.LastName == last_name || last_name == string.Empty)
select user;
Now you will get records that match the first name given, if the first_name is empty all will match as long as it ALSO matches the last name, unless the last_name is blank as well. The only issue with this right now is that if first_name and last_name are blank, you will get everything.
var usersInDatabase =
from user in licenseUserTable
select user;
if (!string.IsNullOrEmpty(first_name)) {
usersInDatabase = usersInDatabase.Where(u => u.FirstName == first_name);
}
if (!string.IsNullOrEmpty(last_name)) {
usersInDatabase = usersInDatabase.Where(u => u.LastName == last_name);
}
This is the single-statement-style approach, but I find Mark's style much cleaner:
var usersInDatabase =
from user in licenseUserTable
where string.IsNullOrEmpty(first_name) || user.FirstName == first_name
where string.IsNullOrEmpty(last_name) || user.LastName == last_name
select user;
精彩评论