Search code examples
c#listentity-frameworklinq

How to check if first item is null in lists (using c#)?


I have this var activityGroup = context.Activity.Where(c => c.ActivityId == activityId).Select(c => c.ActivityGroupId);

If there is no ActivityGroupId "for seome reason " (still don't know why) that query will return a list where the first item is null... how do i check if this list is not null or if it has Any elements?

FYI

  • I know the existence of .Any() but since the first item is null doing .Any() will return true.

  • Is it okay if i do this:
if (activityGroup.Contains(null)) { // do something here }

Solution

  • As the question asks for accessing first item in a list, there is a function in linq that returns the first item in a list.

    Try the following:

    if (activityGroup.First() == null)
    

    There is also another function FirstOrDefault() that allows to handle case of default value if first item is null.

    More in this official Microsoft Documentation

    However, since ActivityGroupId may be null in items other than the first, you need to check for its nullability in the where clause as the following:

    .Where(c => c.ActivityId == activityId && c.ActivityGroupId != null)