misleadingTitle
misleadingTitle

Reputation: 647

Lambda expression to retrieve property which can be null

Basically I've a list of elements in which I've to retrieve a property that can be either null or a costant string. Of course there is a procedural way to do this but since I'm experimenting with lambdas I want to use them.

I've tried to use this lambda:

td.Where(x => !String.IsNullOrEmpty(x.BALANCE_MU)).FirstOrDefault().BALANCE_MU

The problem here is that sometimes all x.BALANCE_MUs are null, so FirstOrDefault() is null and trying to access to BALANCE_MU throws an exceptiom. If all the elements are null I should return an empty string.

Is there a better way to do this staying in the lambda domain?

Upvotes: 2

Views: 5209

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236248

You can project results to avoid exception:

var balance = td.Where(x => !String.IsNullOrEmpty(x.BALANCE_MU))
                .Select(x => x.BALANCE_MU) // select property here
                .FirstOrDefault();

BTW default value for string is not empty string - it is null. If you want to have empty string, then as @newStackExchangeInstance suggested, you can use coalescing operator: balance ?? "".

One more update. You can use oveloaded FirstOrDefault method if you will do projection before filtering:

var balance = td.Select(x => x.BALANCE_MU)
                .FirstOrDefault(b => !String.IsNullOrEmpty(b)) ?? "";

Upvotes: 7

Related Questions