如何解决如何简化Lambda表达式中的多个空检查
我有一个方法,该方法返回按类型或状态过滤的交易。
public IEnumerable<Transaction> GetFilteredTransactions(string type,string status)
{
IEnumerable<Transaction> transactions;
if(type != null && status != null)
{
transactions = Database.Transactions.GetAll().Where(x => x.Type == type && x.Status == status);
}
else if(type != null && status == null)
{
transactions = Database.Transactions.GetAll().Where(x => x.Type == type);
}
else if(type == null && status != null)
{
transactions = Database.Transactions.GetAll().Where(x => x.Status == status);
}
else
{
transactions = Database.Transactions.GetAll();
}
return transactions;
}
我确定可以简化此方法,但是我不知道怎么做。
解决方法
transactions = Database.Transactions.GetAll();
if (type != null)
{
transactions = transactions.Where(x => x.Type == type);
}
if (status != null)
{
transactions = transactions.Where(x => x.Status == status);
}
,
另一种选择是单个lambda表达式:
x =>
(x.Type == null || x.Type == type)
&&
(x.Status == null || x.Status == status)
尽管我不确定这是否比您的代码更具可读性。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。