2014-12-03 103 views
2

我有一个奇怪的行为,使用IEnumerable<string>三元运算符和Select语句。
我有两个不同的对象列表。一个列表包含Enums另一个列表包含对象。这些对象确实有String属性。
如果一个列表是nullempty我想获得另一个列表的值。
下面是一些代码:IEnumerable Select三元运算符语句

public class ExportItem 
{ 
    public string Type; 
    ... 
} 

public enum ExportType 
{ 
    ExportType1, 
    ExportType2, 
    ... 
} 

List<ExportItem>总是由一个配置文件填补。如果提供了命令行参数,则会填充List<ExportType>。所以如果List<ExportType>被填充,我想使用它们,否则我想使用配置文件中的那些。
所以我的代码IST是这样的:

IEnumerable<string> exportTypes = MyListOfExportTypes != null && 
    MyListOfExportTypes.Any() ? MyListOfExportTypes.Select(x => x.ToString()) : 
    MyListOfExportItems.Select(x => x.Type); 

的事情是,exportTypesnull,但我不明白这一点...
当我这样做与if-else一切按预期工作。另外,如果exportTypesList<string>类型,并且在Select声明后我呼叫ToList()一切正常。
使用var a = MyListOfExportTypes.Select(x => x.ToString());var b = MyListOfExportItems.Select(x => x.Type);确实按预期工作。
必须是三元运算符和/或IEnumerable。但是什么?

或我错过了什么?有什么建议么?

编辑:
我现在有截图... enter image description here

需要注意的是上述foreach作品仍然代码...

+0

你怎么知道exportTypes为null? – 2014-12-03 15:12:59

+0

通过调试代码。 – 2014-12-03 15:14:42

+0

如果你调用'exportTypes.ToList'你会得到一个NullReferenceException吗? – 2014-12-03 15:17:14

回答

3

不知道这是回答, 但我认为这与您使用LINQ延迟执行的事实有关。

在编写LINQ查询 时,创建查询和执行查询是有区别的。

编写select语句,正在创建查询,添加ToList()执行它。 想起它就像在SQL服务器控制台(这是写作阶段)中编写SQL查询, ,并且一旦你按F5(或播放按钮),你就执行它。

我希望这个小代码示例将有助于澄清它。

public class SomeClass 
    { 
     public int X { get; set; } 
     public int Y { get; set; } 

     public void Test() 
     { 
      //Here I'm creating a List of Some class 
      var someClassItems = new List<SomeClass> { 
       new SomeClass { X = 1, Y = 1 }, 
       new SomeClass { X = 2, Y = 2 } 
      }; 

      //Here I'm creating a Query 
      //BUT, I'm not executing it, so the query variable, is represented by the IEnumerable object 
      //and refers to an in memory query 
      var query = someClassItems. 
       Select(o => o.X); 

      //Only once the below code is reached, the query is executed. 
      //Put a breakpoint in the query, click the mouse cursor inside the select parenthesis and hit F9 
      //You'll see the breakpoint is hit after this line. 
      var result = query. 
       ToList(); 

     } 
    }