Home > other >  Can I use a LINQ if statement with a boolean... all inside a select new? C#
Can I use a LINQ if statement with a boolean... all inside a select new? C#

Time:07-22

First time working with Linq so I'm not sure if this is the best way to go about what I want to do...any advice is appreciated.

I want to use the boolean m.IsDog to add the word Dog to the end of the m.Behavior string. If it is indeed a dog, then "-Dog" gets added, if not then I just want the m.Behavior.

I have this in my code, and it's been working like I wanted to in the APIs response.

select new ReportCard
{
Id = m.Id,
Name = $"{m.FirstName} {m.LastName}",
Age = m.Age,
Attitude = m.IsDog ? m.Behavior   "-Dog" : m.Behavior

I'm stuck though, because I also want to write something similar to the following:

If m.Behavior = "G" then "Good" else "Bad"

So that my API responses can be "Good-Dog" , "Bad-Dog", "Bad", "Good" without changing the database values.

Is it even possible to do something like that in the same line of code?

CodePudding user response:

Perhaps changing this line from:

Attitude = m.IsDog ? m.Behavior   "-Dog" : m.Behavior

to:

Attitude = (m.Behavior.StartsWith("G") ? "Good" : "Bad")   (m.IsDog ? "-Dog" : "")

would help?

Keep in mind, this would only match Behaviors that match an Upper Case "G".

  • Related