Problems with LINQ query when trying to select from an empty collection

I have the following LINQ query that pulls the final result set from two 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 that I get the following error: Value cannot be null.

I know that the problem is that the usersWithSecurity collection usersWithSecurity empty. I added '.DefaultIfEmpty () `at the end, but it still throws an exception.

How can I modify my LINQ statement to continue and return everything from usersAd and elements from usersWithSecurity , if it exists, and the values ​​match (as shown in lambda)?

+4
source share
3 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 }; 
+2
source

I believe Value cannot be null is a standard message from ArgumentNullException . If you are debugging and extending the error message, you will see the actual parameter name causing the null argument to be thrown.

Are any of usersAd , usersWithSecurity , userRepository null?

EDIT:

Well, with the additional information you provided in your comment, I now see the problem. usersWithSecurity is null, and this cannot be. The source parameter is the name of the IEnumerable or IQueryable in all extension methods found in the Enumerable and Queryable classes.

If you fix this, it should work as you expect, a left join and that’s it.

 usersWithSecurity = usersWithSecurity ?? Enumerable.Empty<User>(); // or similar 
+2
source

Your problem arises when you execute your .ToLower() on an empty var. I recommend avoiding highlighting hidden lines in a loop (in your case, in your Where ). Use String.Compare() .

Here is an example of using your code.

 var results = from usrAd in usersAd from usrRepo in usersWithSecurity.Where(x => string.Equals(usrAd.Value, x.Value, StringComparison.OrdinalIgnoreCase)) select new User(userRepository) { ID = usrRepo == null ? null : usrRepo.ID, Value = usrAd.Value, FullName = usrAd.FullName }; 
+1
source

All Articles