user9065477
user9065477

Reputation:

Add if conditional into anonymouse type

I have a service with query like this:

var periodoConvertido = 2018;

var consultaPendientes = _contexto.Capturas
           .Where(x => x.vEstatus.Equals("L") && x.nPeriodo == periodoConvertido).ToList();

return consultaPendientes;

Now in controller I call that method like :

var res = cs.ConsultarPendientes();

After that in controller I create anonymus type of this method:

res.Where(x => x.Empleado.ID == x.ResponsableID).Select(x => new CapturaVM
        {

            Responsable = x.Empleado.nCodigoEmpleado.ToString() + " - " + x.Empleado.vNombreEmpleado,
            Autorizador = x.Empleado.nCodigoEmpleado.ToString() + " - " + x.Empleado.vNombreEmpleado,

        });

Problem is in anonymous type I want to validate Autorizador parameter like:

if(x => x.SiguienteAutorizadorID  == null){
Autorizador = Responsable
}else{
x.Empleado.nCodigoEmpleado.ToString() + " - " + x.Empleado.vNombreEmpleado 
where x.Empleado.ID == x.ResponsableID
}

How can I add this validation to anonymous type? Regards

Upvotes: 1

Views: 94

Answers (1)

Shaun Luttin
Shaun Luttin

Reputation: 141462

We can use a ternary expression to simulate an if... else... in an anonymous type.

Autorizador = <condition> ? <value when true> : <value when false>;

Example:

using System;
using System.Linq;

public class Program
{
    public static void Main()
    {
        var result = Enumerable
            .Range(1,10)
            .Select((i) => new 
            {
                Value = i,
                IsEven = i % 2 == 0 ? "Even" : "Odd"
            });

        foreach (var r in result)
        {
            Console.WriteLine(r.Value + " is " + r.IsEven);
        }
    }
}

Example Output

1 is Odd
2 is Even
3 is Odd
4 is Even
5 is Odd
6 is Even
7 is Odd
8 is Even
9 is Odd

Upvotes: 2

Related Questions