2017-01-19 60 views
2

我想對TableType應用條件。Linq使用案例

If t.TableName='limit' then TabeType should be A_TypeTable 
If t.TableName='health' then TabeType should be B_TypePolicy 
If t.TableName='waiting' then TabeType should be C_TypeTable 

以下是查詢。我不確定在哪裏分配案件陳述。

var query = from a in tableA 
         join b in tableB on a.Hid equals b.Hid into ab 
         select new 
         { 

          TableType= ab.Select(t=>t.TableName).FirstOrDefault(), 
          UserName = a.UserName, 
          Description = a.Description, 
          ImportedDate = a.ImportedDate 

         }; 

任何意見,將不勝感激。 在此先感謝

回答

2

嘗試像這樣使用三元運算符將它轉換條件情況下,SQL。

var query = from a in tableA 
           join b in tableB on a.Hid equals b.Hid into ab 
           let x= ab.Select(t => t.TableName).FirstOrDefault() 
           select new 
           { 

            TableType = x.equal("limit")? "A_TypeTable" : 
               x.equal("health") ? "B_TypeTable": 
               "C_TypeTable", 
            UserName = a.UserName, 
            Description = a.Description, 
            ImportedDate = a.ImportedDate 

           }; 
1

這可能是一個解決辦法,但你可以做一個嘗試,創建將接受表名作爲字符串,返回表類型爲字符串的方法,該方法的簽名會是這樣:

public string GetTableType(string tableName) 
{ 
    switch (tableName) 
    { 
     case "limit": 
      return "A_TypeTable"; 
     case "health": 
      return "B_TypePolicy";     
     default: 
      return "C_TypeTable"; 
    } 

} 

你可以叫您這樣的查詢方法:

var query = from a in tableA 
        join b in tableB on a.Hid equals b.Hid into ab 
        select new 
        { 
         // Here is the call 
         TableType= ab.Select(t=>GetTableType(t.TableName)).FirstOrDefault(), 
         UserName = a.UserName, 
         Description = a.Description, 
         ImportedDate = a.ImportedDate 

        };