C# Generic List.Any() throws System.NullReferenceException
Asked Answered
D

3

6

Consider the following partial view code snippet

List<sellingPrice> Prices = ViewBag.Prices;
foreach (var mgmp in mg.messageGroup.messageGroupMessagePLUs)
{
    if (Prices.Any(x => x.pluId == mgmp.messagePLU.plu.pluId))
    {
        //do stuff
    }
}

For specific products in the db, the line

if (Prices.Any(x => x.pluId == mgmp.messagePLU.plu.pluId))

throws a System.NullReferenceException. Inspecting the code shows that mgmp is an object and Prices contains elements. However, the value of x is null. Now, I am under the impression that I am simply testing whether or not any "x" exists that satisfies my test, not asking it to return an "x".

It's a very irritating problem. Hopefully someone can point out the really obvious solution.

Dornick answered 16/1, 2013 at 15:14 Comment(0)
O
9

Try:

Prices.Any(x => x!=null && x.pluId == mgmp.messagePLU.plu.pluId)

You might need to do other null checks if for example .messagePLU can be null

Overtrick answered 16/1, 2013 at 15:17 Comment(4)
That did the trick. Thanks. I didn't think it would be necessary in my case to test for nulls in my Prices collection. Ah well, you live and learn.Dornick
One thing to note is that this might only work wit linq-to-objects where the order is guaranteed. I'm not 100% sure but think linq-to-SQL might not short circuit correctly.Overtrick
We'll cross that bridge when we get there.Dornick
You can now use null propagation like (x?.pluId == mgmp.messagePLU?.plu.pluId).Chokedamp
C
2

The most likely reason why this happens is because one or more items in the ViewBag.Prices is null. Check x for null, or see why prices contain nulls in the first place, assuming it's not supposed to have any null values.

Cryptonym answered 16/1, 2013 at 15:18 Comment(0)
S
0

Thanks all for reasoning. An extension to check for list.Any() any even if List is null.

    /// <summary>
    /// Determines whether the collection is null or contains no elements.
    /// </summary>
    /// <typeparam name="T">The IEnumerable type.</typeparam>
    /// <param name="enumerable">The enumerable, which may be null or empty.</param>
    /// <returns>
    ///     <c>true</c> if the IEnumerable is null or empty; otherwise, <c>false</c>.
    /// </returns>
    public static bool IsNullOrEmpty<T>(this ICollection<T> enumerable)
    {
        return enumerable != null && enumerable.Count > 0;
    }
Strobel answered 30/9, 2015 at 3:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.