Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null check String.ToLower in Linq Where expression

Tags:

c#

null

linq

I have this method

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;
}

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?

like image 637
George Taskos Avatar asked Dec 10 '15 21:12

George Taskos


1 Answers

Add this extension method:

public static string NullSafeToLower(this string s)
{
    if (s == null)
    {
        s = string.Empty;
    }
    return s.ToLower();
}

Then replace calls to "ToLower" with calls to "NullSafeToLower."

like image 140
David Alan Condit Avatar answered Sep 19 '22 15:09

David Alan Condit