2016-12-01 88 views
0

以非常簡單的術語,我想在某些情況下將字符串分配給變量。我試圖把if語句放在全局變量的linq語句的外部,但是然後它通過if /然後將字符串賦值給變量,然後在我的excel文件中爲每一行打印出來產生的。如果/然後在Linq聲明

讓我怎麼把類似這樣的

var status = ""; 
if(_db.Owners.Select(i => i.Item1) != null && _db.Owners.Select(i => i.Item2) == null) 
      { 
       status = "S"; 
      } 

到我的LINQ語句聲明說類似於這樣

return _db.Owners 
    .Select(owner => new 
     { 
      CustomerId = owner.Report.CustomerId, 
      IdType = status,//I want this statement to print that status S only where the statement is true 
     } 
+0

你只想與狀態項目= S的返回的集合,或者你只希望在那種情況下打印*? – BradleyDotNET

+1

我不知道我是否正確 - 你只需要'Item1!= null'和'Item2 == null'的'owner'對象以狀態S打印?其他記錄怎麼樣 - 他們有什麼狀態? –

回答

3

我假設IdType是一個字符串,如果語句爲false,您希望它爲空。在這種情況下,你可以使用這個:

return _db.Owners 
    .Select(owner => new 
     { 
      CustomerId = owner.Report.CustomerId, 
      IdType = (owner.Item1 != null && owner.Item2 == null) ? "S": string.Empty, 
    } 

UPDATE 如果要添加第二個情況,你可以這樣做:

return _db.Owners 
    .Select(owner => new 
     { 
      CustomerId = owner.Report.CustomerId, 
      IdType = (owner.Item1 != null && owner.Item2 == null) 
        ? "S" : ([second case condition] ? [value] : string.Empty), 
    } 
+0

如果我想添加第二個案例,我會在寫完後:? – BlowFish

+0

@BlowFish,請參閱我的更新。 –

+1

非常感謝! – BlowFish

1

你可以使用(臭名昭著)三元運營商?

new { 
    CustomerId = owner.Report.CustomerId, 
    IdType = yourTestExpressionFromTheIfAbove ? "S" : string.Empty 
} 

這是你在問什麼?你只是想內聯表達式並刪除外部(臨時)變量?

0

我會做這樣的事:

return _db.Owners 
    .Select(owner => new 
    { 
     CustomerId = owner.Report.CustomerId, 
     IdType = owner.Item1 != null && owner.Item2 == null ? "S" : [your other value] 
    }) 
    .ToList(); 

其中[您的其他值]是任何你想要的狀態,如果記錄不符合您的條件。