How to make if statement inside linq

I have the following expression

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

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

+4
source share
3 answers

Use the ternary operator in the LINQ expression.

You can do something like this:

 References = (g.SelectMany(entry => entry.References).Count() == 0) ? g.SelectMany(entry => entry.References).OrderBy(t => t).ToList() : null; 
+2
source

Use ?: Operator

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

How about this

+4
source

Another way:

 Select(g => { var obj = new AssembledPartsDTO { References= ... }; if (obj.References.Count == 0) { obj.References.Add("??"); } return obj; }) 

You may need this for more complex logic where the ternary operator (?) Is not applied.

+2
source

Source: https://habr.com/ru/post/1483331/


All Articles