2016-12-01 48 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(); 

其中[您的其他值]是任何你想要的状态,如果记录不符合您的条件。