Ray
Ray

Reputation: 4929

String conditions inside lambda

I have the following LINQ expression where I need to concatenate strings, however, I only want to display the hyphen if there are values in the subsequent strings that follow. For example, if there is a Wing and a Floor only, I should only display East-3. I tried to insert some string.IsNullOrEmpty() inside the expression but the compiler complains at the Select keyword...

param.Patient.PatientGroups.Select(g => g.Wing + "-" + g.Floor + "-" + g.Room + "-" + g.Bed + "-" + g.Table).FirstOrDefault()

Upvotes: 1

Views: 150

Answers (1)

Patrick Hofman
Patrick Hofman

Reputation: 156918

You could use string.Join, but you have to convert the fields to an array first:

param.Patient.PatientGroups
    .Select( g => String.Join( "-"
                             , (new string[] { g.Wing, g.Floor, g.Room, g.Bed, g.Table })
                               .Where(x => !string.IsNullOrEmpty(x))
                             )
           ).FirstOrDefault()

Upvotes: 7

Related Questions