LINQ查询中使用的C#三元运算符 [英] C# Ternary Operator used in LINQ query

查看:547
本文介绍了LINQ查询中使用的C#三元运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用三元运算符来反映这种逻辑?

Is it possible to use the ternary operator to reflect this logic?

if (a = 1)
{
    somevalue = "hello";
} 
else if (a = 2)
{
    someValue = "world";
}
else if (a = 3)
{
    someValue = "hellWorld";
}

我正在LINQ查询中执行以下操作:

I am doing the following in a LINQ Query:

using (var data = new DAL())
{
    var result = data.Holidays.AsNoTracking()
                 .Where(x => x.RequesterId == userId)
                 .Select(x => new HolidayModel
                 {
                     HolidayId = x.HolidayId,
                     FromDate = x.FromDate,
                     ToDate = x.ToDate,
                     AuthorisationStatus = x.InternalHolidayStatus == 1 ?
                         HolidayAuthStatus.Pending :
                         HolidayAuthStatus.Rejected,
                     DateModified = x.ModifiedDate
                 }).ToList();

    return Json(result.ToDataSourceResult(request));
}

HolidayAuthStatus是一个枚举,其中具有三个值(Pending(1),Authorised(2)和Rejected(3));并且我想在分配AuthorisationStatus的值时在代码中体现这一点.

HolidayAuthStatus is an enum, which has three values in it (Pending (1), Authorised (2) and Rejected (3)); and I would like to reflect this in code when assigning the value of AuthorisationStatus.

推荐答案

对此进行更改

AuthorisationStatus = (HolidayAuthStatus)x.InternalHolidayStatus

如果HolidayAuthStatus的整数值与InternalHolidayStatus值匹配,则它将起作用.三元运算符在这里看起来很可怕.如果您的状态码不匹配,最好使函数接受int status并返回HolidayAuthStatus

if integer values for your HolidayAuthStatus match InternalHolidayStatus values it will work. Ternary operator here will look horible. If your status code doesn't match it's better to make function accepting int status and returning HolidayAuthStatus

HolidayAuthStatus GetStatus(int status)
{
    if(status == 1) return HolidayAuthStatus.Pending;
    if(status == 2) return HolidayAuthStatus.Authorised;
    if(status == 3) return HolidayAuthStatus.Rejected;
    return HolidayAuthStatus.Unknown; // for e.g.
}

并像这样使用它:

AuthorisationStatus = GetStatus(x.InternalHolidayStatus)

@James说,该方法仅在Linq-to-object中有效,而在Linq-to-entities中无效

as @James said method will work only in Linq-to-object not in Linq-to-entities

这篇关于LINQ查询中使用的C#三元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆