简体   繁体   English

Linq if-elseif-else在asp.net中使用linq查询

[英]Linq if-elseif-else using linq query in asp.net

In my asp.net application i am using linq. 在我的asp.net应用程序中,我正在使用linq。 I need a help what is the syntax for if-elseif-else using linq in single line. 我需要帮助,在单行中使用linq的if-elseif-else的语法是什么。

genericReportList =
    (from CD in list
    select new GENERICREPORT
        {
            CITATIONNO = CD.CITATIONNO,
            DATE = CD.DATE,
            LOCATION = CD.LOCATION,
            //STATUS = CD.STATUS,
            PLATENO = Utilities.DecryptData(CD.PLATENO),
            PSOURCE = CD.PSOURCE,
            MAKE = CD.MAKE,
            ID = Utilities.DecryptData(CD.ID),
            NATIONALITY = CD.NATIONALITY,
            SOURCE = CD.SOURCE,
            NAME = Utilities.DecryptData(CD.NAME),
            VIOLATION = CD.VIOLATION,
            STATUS = CD.STATUS == short.Parse("1") ? "Complete" : "Incomplete"
        }).ToList();


If STATUS = CD.STATUS == short.Parse("1") ? "Complete" : and 2 for "Incomplete" and 3 for "Void"

I don't understand why you are doing short.Parse("1") . 我不明白您为什么要做short.Parse("1") This will always be 1. If you want multiple if-else in a one-liner, combine ternary operators: 它将始终为1。如果您希望在一个直线上使用多个if-else,请组合三元运算符:

STATUS = CD.STATUS == 1 ? "Complete" : CD.STATUS == 2 ? "Incomplete" : "Void"

If this is going to be used in the context of Entity Framework (or other ORM with IQueryable support), it will translate to a CASE WHEN SQL statement. 如果要在Entity Framework(或具有IQueryable支持的其他ORM)的上下文中使用它,它将转换为CASE WHEN SQL语句。

What I understand from your question if I'm not wrong, is that you might be asking about where clause. 如果我没记错,我从您的问题中了解到的是,您可能正在询问where子句。

if yes then you can always use multiple where in your query. 如果是,那么您始终可以在查询中使用多个位置。

example : 
Collection.Where(x => x.Age == 10)
      .Where(x => x.Name == "Fido")
      .Where(x => x.Fat == true)

more about LINQ query 有关LINQ查询的更多信息

http://msdn.microsoft.com/en-us/library/gg509017.aspx http://msdn.microsoft.com/en-us/library/gg509017.aspx

您可以继续使用已有的内容。

STATUS = CD.STATUS == 1 ? "Complete" : (CD.STATUS == 2 ? "Incomplete" : "InProgress")

There nothing wrong with writing your own method and using it in a LINQ query. 编写自己的方法并在LINQ查询中使用它没有任何问题。 It will be far more understandable and readable than a long conditional operator. 它比长条件运算符要容易理解和可读得多。

Consider using something like: 考虑使用类似:

private String GetStatus(int value)
{
    if (value == 1)
        return "Complete";
    if (value == 2)
        return "Incomplete";
    if (value == 3)
        return "Void";

}

Then you would call it like: 然后,您将这样称呼它:

STATUS = GetStatus(CD.STATUS)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM