【问题标题】:Add if conditional into anonymouse type将 if 条件添加到匿名类型
【发布时间】:2018-02-23 19:26:16
【问题描述】:

我有这样的查询服务:

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】:

    我们可以使用三元表达式来模拟匿名类型的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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多