Search code examples
c#linq-to-objects

How can the input parameter of a LINQ to Objects expression be null


I have a collection of objects that I am trying to query with LINQ. Inexplicably, the code is crashing when querying for a specific value.

SomeObject[] myObjects = { ... };

foreach (int id in someIDs)
{
    SomeObject singleObject = myObjects.FirstOrDefault(x => x.ID = id);
}

This code is failing when the value of id is a specific value. The error I get is that x is NULL. The myObjects array is not NULL, and does contain an object with an ID value that matches the value of id that is failing. Other values of id do not cause the error. When id is the value that is failing, I can step through the LINQ expression as it iterates through the items in the array. The parameter x has a value for every item in the collection up until it reaches the item before the item that matches the problematic value of id; at that point x suddenly becomes NULL and an exception is thrown.

How could the input parameter of a LINQ expression on a non-NULL collection ever be NULL? Even if the collection did not contain an item with ID matching id, it should just return the default value for my object type, not crash with a NULL error.


Solution

  • Fix the nulls and improve runtime performance drastically like so:

    SomeObject[] myObjects = new[] { ... };
    
    Dictionary<Int32,SomeObject> dict = myObjects
        .Where( mo => mo != null )
        .ToDictionary( mo => mo.id );
    
    foreach( Int32 id in someIds )
    {
        if( dict.TryGetValue( id, out SomeObject singleObject ) )
        {
            // do stuff here
        }
        else
        {
            // don't do stuff here
        }
    }