Home > Back-end >  How to check if first item is null in lists (using c#)?
How to check if first item is null in lists (using c#)?

Time:09-21

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 }

CodePudding user response:

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)

CodePudding user response:

var activityGroup = context.Activity
  .Where(c => && c.ActivityGroupId != null && c.ActivityId == activityId)
  .Select(c => c.ActivityGroupId);
var hasActivityGroup = activityGroup.Any();

This is correct syntax, the other proposed solution will still throw null pointer exceptions, when ActivityGroupId is null.

CodePudding user response:

As one of the tags is "Entity Framework", I suggest an approach that filters when retrieving data from the database. If you are interested only in not-null items, you can extend the Where-clause:

var activityGroup = context.Activity
  .Where(c => c.ActivityId == activityId && c.ActivityGroupId != null)
  .Select(c => c.ActivityGroupId);
var hasActivityGroup = activityGroup.Any();

The above approach filters directly in the database so that only data are transferred, that contain an ActivityGroupId.

  • Related