c# .net 4.0 : nullable input string parameter and

2019-08-18 22:18发布

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

3条回答
▲ chillily
2楼-- · 2019-08-18 22:47

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
查看更多
时光不老,我们不散
3楼-- · 2019-08-18 22:56

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.

查看更多
相关推荐>>
4楼-- · 2019-08-18 22:57
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.

查看更多
登录 后发表回答