将条件添加到匿名类型中

问题描述 投票:1回答:1

我有一个像这样的查询服务:

var periodoConvertido = 2018;

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

return consultaPendientes;

现在在控制器中我称之为:

var res = cs.ConsultarPendientes();

之后在控制器中我创建此方法的匿名类型:

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,

        });

问题是匿名类型我想验证Autorizador参数,如:

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

如何将此验证添加到匿名类型?问候

c# asp.net linq anonymous-types
1个回答
2
投票

我们可以使用三元表达式来模拟匿名类型的if... else...

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);
        }
    }
}

示例输出

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
© www.soinside.com 2019 - 2024. All rights reserved.