STORM
STORM

Reputation: 4331

Why is IEnumerable<object> not null after LINQ query?

I have a List which holds > 10.000 items. I am doing a LINQ query on this

IEnumerable<Term> terms = from t in regionCollection
                           where t.Name == strRegion
                           select t;

if (terms != null)
{
    m.RegId = Convert.ToInt32(terms.FirstOrDefault().CustomProperties["dbId"]);
}

If (terms !=null) is always not null! I have a feeling that the query is executed only if i try to access the single object inside the IEnumarable. Is this correct and if yes how can i check if my IEnumarable is not null?

Upvotes: 1

Views: 597

Answers (1)

dotnetom
dotnetom

Reputation: 24901

Variable term will always have a value, it will never be null, because if query returns no results then terms will be empty enumerable. In your case you can update the code like this:

// Get first item of query or default value
var firstTerm = terms.FirstOrDefault();
// If there were no items, then firstTerm is null
if (firstTerm != null)
{
    // This code block is only executed if the query had at least 1 item in results
    m.RegId = Convert.ToInt32(firstTerm.CustomProperties["dbId"]);
}

Upvotes: 5

Related Questions