TechAnc
TechAnc

Reputation: 111

How to check null in lambda expression

How to check for null in where condition in lambda expression?

listdropdownid.Id = listgroupid.Where(X => X.abc == desc).FirstOrDefault().abc_id.ToStr();
listdropdownid.Desc = desc;

If abc == desc fails, I need to assign null to listdropdownid.Id.

Upvotes: 0

Views: 315

Answers (3)

Tim Schmelter
Tim Schmelter

Reputation: 460108

The most elegant way is to specify another default value using DefaultIfEmpty(newValue):

listdropdownid.Id = listgroupid
    .Where(x => x.abc == desc)
    .Select(x => x.abc_id.ToString())
    .DefaultIfEmpty(null)  // would be more useful if you'd provide a more meaningful value like "<not found>"
    .First;

That works even with value types, in this case you could also use FirstOrDefault since the default value of string is already null. You just have to select it:

listdropdownid.Id = listgroupid
    .Where(x => x.abc == desc)
    .Select(x => x.abc_id.ToString())
    .FirstOrDefault();

Upvotes: 1

Sushant Srivastava
Sushant Srivastava

Reputation: 761

do this

listdropdownid.Id = listgroupid.Where(X=>X!=null).Where(X => X.abc == desc).FirstOrDefault().abc_id.ToStr();

Upvotes: 0

Relax
Relax

Reputation: 283

This should help you:

listdropdownid = listgroupid.Where(X => X.abc == desc).FirstOrDefault();
if (listdropdownid != null)
{
   // Do something with listdropdownid.Id
}

Upvotes: 0

Related Questions