Home > database >  Comparing Nullable long with Long in C#
Comparing Nullable long with Long in C#

Time:02-18

What are we supposed to do when db column is Nullable long, here (Visit) and I have VisitorIds to compare with?

long[] VisitorIds = new long[] {1,2,3}; //an array to check with

    .Where(x => vivitorIds.Contains(x.Visit)).ToList();

If I convert to long in linq, it is throwing exception .

.Where(x => vivitorIds.Contains(Convert.ToInt64(x.Visit))).ToList();

CodePudding user response:

Just check if the nullable has a value:

.Where(x => x.Visit.HasValue && vivitorIds.Contains(x.Visit.Value)).ToList();

CodePudding user response:

We can use null conditional operator with null coalescing,

//Considering long.MinValue is not a part of vivitorIds list.
.Where(x => vivitorIds.Contains(x?.Visit?.Value ?? long.MinValue)).ToList();

Note: This is just an alternate approach, Tim's solution is cleaner than this solution

  • Related