2013-07-18 39 views
2

我使用lambda語句設置我的foreach循環:是否有Lambda Else條件?

foreach (Shape shape in shapefile.Where(x=>x.GetMetadata(IgnoreField) != IgnoreValue)) 

IgnoreFieldIgnoreValue可選參數。

如果這些字段爲空(未使用),我怎麼能改變我的foreach來解釋這個?有沒有其他的陳述或類似的東西?

回答

2
foreach (Shape shape in shapefile.Where(x=>IgnoreField==null || IngoreValue==null || x.GetMetadata(IgnoreField) != IgnoreValue)) 
+0

我該如何解釋這是如何工作的?這看起來像是我正在尋找的答案,我只是想要解釋它的能力,以便稍後在筆記中提醒自己。 – webdad3

+1

該表達式與您的具有2個附加條件的表達式相同,用於檢查全局IgnoreField和IgnoreValue參數是否爲空。因此,如果這些參數中的任何一個爲空,則將檢索所有項目。如果兩者都不爲空,則所有項目都將根據條件進行過濾。 – Tilak

+0

由於'IgnoreField'和'IngoreValue'在迭代期間不會改變,所以最好在迭代之前檢查它們,而不是'shapefile'中的每個值。 – Servy

3

這不是魔術。你會使用拉姆達之外,請正是:

foreach (Shape shape in shapefile.Where(x=> 
    (x.IgnoreField != null && // If both optional fields are present 
    x.IgnoreValue != null && 
    x.GetMetadata(IgnoreField) != IgnoreValue) // Then only where metadata for 
               // ignored field is not the ignored value 
    || 
    (x.IgnoreField == null || x.IgnoreValue == null))) // But if either field absent 
                 // then return all data 
+0

這對我來說不是可選的......我沒有得到什麼? –

+0

如果兩個可選字段中的一個不存在,OP沒有說他想要檢索哪個數據。如果其中一個可選字段不存在,我會將其更改爲返回所有行。 –

+0

IgnoreField和IgnoreValue不是shapefile的一部分,它們是通過ini文件填充的真正的全局變量。對此我並不清楚。所以我認爲我可以使用||的一切部分。 – webdad3

4

我想你想要的是......如果他們沒有空......然後檢查他們......但如果是空然後忽略他們吧?

foreach (Shape shape in shapefile.Where(x=> 
    x.IgnoreField == null || 
    x.IgnoreValue == null || 
    x.GetMetadata(IgnoreField) != IgnoreValue) 

另請注意,當您縮進LinQ時,如何更容易地看到它在做什麼?

另一種格式化技術我用的,尤其是在foreach語句一樣,這是在一個適當命名的變量中枚舉存儲在像這樣的foreach語句使用它之前...

var shapesFilteredByIgnores = shapefile.Where(x=> 
    x.IgnoreField == null || 
    x.IgnoreValue == null || 
    x.GetMetadata(IgnoreField) != IgnoreValue) 

foreach (Shape shape in shapesFilteredByIgnores) 

當然,這是隻有當你有一個有意義的變量名來分配它時纔會更清楚。

+0

我覺得第二個'null'檢查是不必要的,因爲如果任何一個都是'null',那麼你不能得到那麼遠。 –

+0

@Sahuagin你的權利......更新邏輯以反映它。 – Kevin

2

您可以簡單地套用有條件根據您是否擁有值檢查Where

var query = shapefile.AsEnumerable(); 

if(IgnoreField!=null && IngoreValue!=null) 
    query = query.Where(x=>x.GetMetadata(IgnoreField) != IgnoreValue); 

foreach (Shape shape in query) 
    {...} 

與這裏其他的答案,這並不刻意去檢查這兩個領域的null每個項目在序列中;它會檢查一次並只在可以時才應用過濾器。