devludo
devludo

Reputation: 123

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


if (activityGroup.Contains(null)) { // do something here }

Upvotes: 0

Views: 660

Answers (3)

Wael Moughrbel
Wael Moughrbel

Reputation: 244

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)

Upvotes: 2

Markus
Markus

Reputation: 22436

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.

Upvotes: 0

Morten Bork
Morten Bork

Reputation: 1632

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.

Upvotes: 0

Related Questions