Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Query Issues when trying to select from empty collection

Tags:

c#

linq

I have the following LINQ query that is pulling a final resultset from 2 collections: usersAd and usersWithSecurity:

var results = from usrAd in usersAd
              from usrRepo in usersWithSecurity
                             .Where(x => usrAd.Value.ToLower() == x.Value.ToLower())
                             .DefaultIfEmpty()
      select new User(userRepository)
      {
        ID = usrRepo == null ? null : usrRepo.ID,
        Value = usrAd.Value,
        FullName = usrAd.FullName
      };

The problem is I keep getting the following error: Value cannot be null.

I know the issue is that the usersWithSecurity collection is empty. I added the '.DefaultIfEmpty()` on the end but it still produces the exception.

How can I modify my LINQ statement to go ahead and return everything from usersAd and items from usersWithSecurity if it exists and the values match (as shown in the lambda)?

like image 503
atconway Avatar asked Sep 24 '13 18:09

atconway


2 Answers

var usersWithSecurity = _biz.getUsersWithSecurity() ?? new List<User>();

var results = from usrAd in usersAd
              from usrRepo in usersWithSecurity
              where usrAd.Value.ToLower() == usrRepo.Value.ToLower()
              select new User(userRepository)
              {
                  ID = usrRepo == null ? null : usrRepo.ID,
                  Value = usrAd.Value,
                  FullName = usrAd.FullName
              };
like image 118
hunter Avatar answered Oct 11 '22 17:10

hunter


I believe that Value cannot be null is the standard message from an ArgumentNullException. If you're debugging, and you expand on the error message, you'll see the actual parameter name that is causing the argument null exception.

Are any of usersAd, usersWithSecurity, userRepository null?

EDIT:

Okay, with more information provided from you in your comment, I now see the issue. usersWithSecurity is null, and it can't be. The source parameter is the name for the source IEnumerable or IQueryable in all of the extension methods found in the Enumerable and Queryable classes.

If you fix that, it should work as you expect, left join and all.

usersWithSecurity = usersWithSecurity ?? Enumerable.Empty<User>(); // or similar
like image 41
Christopher Currens Avatar answered Oct 11 '22 17:10

Christopher Currens