2014-12-03 94 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(); 

     } 
    }