我有以下方法:
public IQueryable<Profile> FindAllProfiles(string CountryFrom, string CountryLoc)
{
return db.Profiles.Where(p => p.CountryFrom.CountryName.Equals(CountryFrom,
StringComparison.OrdinalIgnoreCase));
}
编写在一个语句中过滤所有可能的输入参数组合的 where 子句的最佳方式是什么:
CountryFrom 和 CountryLoc = null
仅国家/地区From null
仅 CountryLoc 为空
CountryFrom 和 CountryLoc 都不为空。
很快..我需要按年龄、性别、职业过滤个人资料..只要你能想到的。
我正在尝试找到一种用 C# 高效编写它的方法。我知道如何在 TSQL 中以干净的方式完成它。我希望我知道路。感谢迄今为止所有的回复。
最佳答案
一个好的旧式二进制 XNOR 运算就可以解决这个问题:
db.Profiles.Where(p => !(p.CountryFrom == null ^ p.CountryTo == null))
它实际上等于两个 bool 值,尽管对我来说,它比写 ((p.CountryFrom == null) == (p.CountryTo == null))
更直接,更简单。 !
关于C# 处理所有可能的空值和非空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3196744/