c# .net 4.0 : nullable input string parameter and the lambda expressions

▼魔方 西西 提交于 2019-12-14 03:11:53

问题


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


回答1:


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.




回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/3191687/c-sharp-net-4-0-nullable-input-string-parameter-and-the-lambda-expressions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!