views:

77

answers:

3

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 or last_name is blank then I want to still evaluate the other data item.

+4  A: 
    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);
    }
Mark Byers
+2  A: 
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.

David
Instead of first_name==string.Empty, you maybe could also use String.IsNullOrEmpty(first_name).
Hans Kesting
I was going to put that, but I do not believe that string.IsNullOrEmpty is valid in LINQ. It does work in Entity framework though.
David
A: 

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;
Nick Craver