Is a Collection Null
var customers = new List<BECustomer>();
customers = GetCustomers();
But I don't underst开发者_JS百科and why customers[0] == null
even if
customers.Any()==true
or
customers.Count == 1
or
customers==null
is false
How do I check for null customers?
This is a difference.
You list is not null since you instantiated it with new List() and then assign getCustomers(). Maybe this is returning null.
But an element in the list can be null. For example:
customers[0] = null
Then you have set the first element in the array to null.
So to summarize:
if (customers == null)
Checks if the customerzs variable points to null
if (customers[0] == null)
Checks if the first element in the array is null
Try the following:
customers.Any(c => c == null)
You can check that with customers.Contains(null)
. See more here.
If you want to check if any item of a collection is null, you can use this extension method.
public static bool AnyNull<T>(this IEnumerable<T> items)
where T : class
{
return items.Any(item => item == null);
}
Usage:
var customers = GetCustomers();
bool anyCustomerNull = customers.AnyNull();
new List<BECustomer().Add(null)
will have the same effect. Non-null, non-empty list whch contains null
element./
Because there is one customer, that is set to null
.
精彩评论