Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make if statement inside linq

Tags:

c#

linq

I have following statement

Select(g => new AssembledPartsDTO
{
..
..
    References = g.SelectMany(entry => entry.References).OrderBy(t => t).ToList()
..
..
}

How I can add if References.count == 0 than Add("??") to References?

like image 880
Night Walker Avatar asked Feb 16 '23 09:02

Night Walker


2 Answers

Use ?: Operator

References.count > 0 ? References : new List<string>(){"??"}

How about that

like image 121
Colonel Panic Avatar answered Feb 28 '23 06:02

Colonel Panic


Use a ternary operator in your LINQ expression.

You could do something like this;

References = (g.SelectMany(entry => entry.References).Count() == 0)
   ? g.SelectMany(entry => entry.References).OrderBy(t => t).ToList() : null;
like image 30
wonea Avatar answered Feb 28 '23 05:02

wonea