views:

57

answers:

3

I have a following method:

public IQueryable<Profile> FindAllProfiles(string CountryFrom, string CountryLoc)
{


    return db.Profiles.Where(p => p.CountryFrom.CountryName.Equals(CountryFrom,StringComparison.OrdinalIgnoreCase));

}

Right now, it just filters by CountryFrom but I need to filter it by CountryLoc as well. So how do I modify the Where filter?

Also, CountryFrom could be null or CountryLoc could be null. So how do I modify the method's signature to all the nullable input string parameter.

I know how to do this in SQL but I am not sure about lambda expressions or LINQ.

Thanks

+2  A: 

Your question isn't actually LINQ-specific. You can put any boolean conditions inside the lambda that you want, such as:

p => p.CountryFrom.CountryName.Equals(...) && p.CountryLoc.CountryName.Equals(...)

To handle null values you can use the static string.Equals method instead, like this:

p => string.Equals(p.CountryFrom.CountryName, CountryName, StringComparison.OrdinalIgnoreCase)

If this starts getting too long you could always extract it into a method.

Evgeny
A: 
return db.Profiles
    .Where(p => p.CountryFrom.CountryName.Equals(CountryFrom, 
        StringComparison.Ordinal.IgnoreCase) && 
        p.CountryLoc.CountryName.Equals(CountryLoc,
        StringComparison.Ordinal.IgnoreCase));

Sorry...there was no way to make that statement pretty.

Just remember you can use any boolean logic you'd like inside of the Where extension method. It's just as easy as it would be anywhere else.

Also, a string parameter can be null no matter what (it's a reference type) so you don't need to worry about making things nullable.

Justin Niessner
I think the asker is concerned about the Equals method throwing NullReferenceException.
Evgeny
A: 

You'll want to use the logical and operator "&&" in your lambda expression to filter by both CountryFrom and CountryLoc. Ex

db.Profiles.Where(p => p.CountryFrom == CountryFrom && p.CountryLoc == CountryLoc);

In C# strings are reference types and therefore can be null. You can check for null values using

myString == null
Wesley Wiser