Arnab Das
Arnab Das

Reputation: 3728

Dealing with a null column in LINQ while concatenate to a string

I'm trying to fetch person details, where middle name is missing some times, in my application. I'm trying with like this:

contactTable.Select(c => c.Title + " " + c.FirstName).ToList();

But whenever the title column remains null in DB, it returns empty for that entry. I want some kind of like:

contactTable.Select(c => (string.IsNullOrEmpty(c.Title) ? "" : c.Title + " ") + c.FirstName).ToList();

Is this possible in one linq statement? Thanks in advance.

This is possible and the complete answer is including the nullable MiddleName:

contactDetails = contactTable.Select(c =>
            ((c.Title ?? "") + " " + c.FirstName).Trim() + " " + ((c.MiddleName ?? "") + " " + c.LastName).Trim()).ToList();

See the double use of Trim().

Upvotes: 2

Views: 2849

Answers (1)

Pranay Rana
Pranay Rana

Reputation: 176896

Make use of : ?? Operator

try this below code

contactTable.Select(c => ( (( c.Title ?? "") + " "  + c.FirstName).Trim()).ToList();

Upvotes: 3

Related Questions