在Linq Where表达式中对Null检查String.ToLower [英] Null check String.ToLower in Linq Where expression
本文介绍了在Linq Where表达式中对Null检查String.ToLower的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这种方法
private IList<Order> FilterOrders(string filterText)
{
string filterTextLowerCase = filterText.ToLower();
var filtered = _orders.Where(order =>
order.OrderIdFullOrderNumber.ToLower().Contains(filterTextLowerCase) ||
order.Name.ToLower().Contains(filterTextLowerCase) ||
order.Status.ToLower().Contains(filterTextLowerCase) ||
order.TimeRemaining.ToLower().Contains(filterTextLowerCase) ||
order.Address.ToLower().Contains(filterTextLowerCase) ||
order.City.ToLower().Contains(filterTextLowerCase) ||
order.State.Abbrev.ToLower().Contains(filterTextLowerCase) ||
order.PostalCode.ToLower().Contains(filterTextLowerCase)).ToList();
return filtered;
}
如您所见,属性中可能存在null引用异常,那么在此Where表达式中检查null的最佳方法是什么?
As you can see there's a possible nullreference exception in properties, what would be the best way to check for null in this Where expression?
推荐答案
很遗憾,目前我无法使用C#6.0功能.
Unfortunately I couldn't use C# 6.0 features at this point.
我最终创建了一个扩展方法来过滤列表,然后与另一个扩展方法Contains进行比较,该方法接受@ robert-mckee的建议并接受@ jeppe-stig-nielsen的演示,接受一个StringComparison参数.
I ended up creating an extension method to filter the list, comparing with another extension method, Contains, that accepts a StringComparison parameter as suggested from @robert-mckee and demonstrated from @jeppe-stig-nielsen.
public static IList<Order> FilterOrders(this IList<Order> orders, string filterText)
{
var filtered = orders.Where(order =>
order.OrderIdFullOrderNumber.Contains(filterText, StringComparison.OrdinalIgnoreCase) ||
order.Name.Contains(filterText, StringComparison.OrdinalIgnoreCase) ||
order.Status.Contains(filterText, StringComparison.OrdinalIgnoreCase) ||
order.TimeRemaining.Contains(filterText, StringComparison.OrdinalIgnoreCase) ||
order.Address.Contains(filterText, StringComparison.OrdinalIgnoreCase) ||
order.City.Contains(filterText, StringComparison.OrdinalIgnoreCase) ||
order.State.Abbrev.Contains(filterText, StringComparison.OrdinalIgnoreCase) ||
order.PostalCode.Contains(filterText, StringComparison.OrdinalIgnoreCase)).ToList();
return filtered;
}
public static bool Contains(this string source, string value, StringComparison comparison)
{
if (string.IsNullOrWhiteSpace(source))
{
return false;
}
return source.IndexOf(value, comparison) >= 0;
}
这篇关于在Linq Where表达式中对Null检查String.ToLower的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文