Issue with Object returned when using Linq Where clause
I have the following code:
IList<CmsUserPermissionGroup> matchingRoles = 开发者_Python百科PermissionGroups.Where(r => r.JournalCode.ToLower() == journalCode.ToLower())
.Where(r => r.CmsRole.ToLower() == role.ToLower())
.Where(r => r.AccessLevel > 0)
that I assumed would return an empty List if no results are returned. What is actually returned is the following error:
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Am I misunderstanding something? What other alternative is there?
If there was no problem with the query, an empty enumeration would be returned.
The problem here is inside your Where()
statements. Either JournalCode
or CmsRole
are null (assuming you already checked journalCode
and role
for null values somewhere else) on one of the objects in PermissionGroups
. When you call ToLower()
on that value, it throws the above Exception.
You could protect yourself a little better with the following:
if(!String.IsNullOrEmpty(journalCode) && !String.IsNullOrEmpty(role))
{
Roles =
PermissionGroups
.Where(r => r.JournalCode != null
&& r.JournalCode.Equals(journalCode,
StringComparison.InvariantCultureIgnoreCase))
.Where(r => r.CmsRole != null
&& r.CmsRole.Equals(role,
StringComparison.InvariantCultureIgnoreCase))
.Where(r => r.AccessLevel > 0);
}
It will return an empty sequence if no results are returned and the predicates succeeded.
As it happens, it looks like either r
was null for some element, or r.JournalCode
was null for some element, or journalCode
was null, or r.CmsRole
was null for some element, or role
was null. LINQ doesn't prevent these exceptions from bubbling up.
精彩评论