2012-02-29 88 views
0

我正在嘗試遍歷字符串列表並檢查它們是否針對單個字符串。如果沒有找到匹配,那麼我們需要退出代碼。如果只有1中設置字符串,但只要你有多個字符串,如果第一個不匹配明顯的代碼退出太早只有在沒有匹配的情況下循環遍歷列表和「返回」

// loadedObj.Settings contains the list of strings, can be any number of strings  
foreach (var currentCheckBox in loadedObj.Settings.Where(currentCheckBox => currentCheckBox != null)) 
    { 
     // docTypeAlias is a single string that needs to be matched 
     var docTypeAlias = sender.ContentType.Alias; 
     // This is the current value of currentCheckBox 
     var requiredTypeAlias = currentCheckBox; 
     if (!requiredTypeAlias.Equals(docTypeAlias)) return; 
    } 

的代碼工作正常。

+0

'currentCheckBox'似乎是一個CheckBox。 CheckBox如何成爲一個字符串列表?你的代碼也會嘗試任何與你的文本無關的東西。你可以編輯來澄清類型,你的實際目標是什麼? – 2012-02-29 00:53:44

+0

爲什麼不使用常規的'foreach'循環? – udidu 2012-02-29 00:55:51

+0

對不起,這是從其他代碼複製的名稱,它實際上是從xml文件讀入的checkBox項目列表。 – 2012-02-29 01:04:19

回答

1

您可以使用Any來查看序列中是否有任何元素符合您的條件。如果沒有,結果將是錯誤的。

var docTypeAlias = sender.ContentType.Alias; 
bool hasMatch = loadedObj.Settings.Any(current => docTypeAlias.Equals(current)); 
if (hasMatch) 
{ 
    // can work 
} 
else 
{ 
    // can't work 
} 
+0

這對Anthony很有幫助,非常感謝。 – 2012-02-29 01:04:39

+0

+1爲心理答案。 :) – 2012-02-29 01:08:43

0

看起來你想要的「繼續」(跳過的foreach的代碼的其餘部分,並檢查下一個項目),而不是從函數返回「回報」。

考慮使用FirstOrDefault,如果您只需檢查集合上的某些謂詞。

+1

'繼續'?這是循環中的最後一個陳述.. – paislee 2012-02-29 00:52:55

+0

代碼在我看來就像縮短的樣本 - 伊恩霍頓應該做的事情,如果「發現」的情況下...但是樣本,因爲它是繼續是沒用的。我認爲樣本是JQuery.each的翻譯,其中返回將基本上繼續。 – 2012-02-29 00:56:46

1

添加一個布爾值來記錄答案。

bool found = false; 
foreach (var currentCheckBox in loadedObj.Settings.Where(currentCheckBox => currentCheckBox != null)) 
{  
    // docTypeAlias is a single string that needs to be matched 
    var docTypeAlias = sender.ContentType.Alias; 
    // This is the current value of currentCheckBox 
    var requiredTypeAlias = currentCheckBox; 
    if (requiredTypeAlias.Equals(docTypeAlias)) { 
     found = true; 
     break; 
    } 
} 
if (!found) return; 

或者,這讓一個單獨的函數:

bool ControlIsListed(object sender, MySettingsClass loadedObj) 
{ 
    foreach (var currentCheckBox in loadedObj.Settings.Where(currentCheckBox => currentCheckBox != null)) 
    {  
     // docTypeAlias is a single string that needs to be matched 
     var docTypeAlias = sender.ContentType.Alias; 
     // This is the current value of currentCheckBox 
     var requiredTypeAlias = currentCheckBox; 
     if (requiredTypeAlias.Equals(docTypeAlias)) return true; 
    } 
    return false; 
} 

裏調用:

private void eventhandler(object sender, EventArgs e) 
{ 
    if (!ControlIsListed(sender, loadedObj)) return; 
    // ... 
} 
0
bool doAnyMatch = loadedObj 
        .Settings 
        .Where(x => x != null) 
        .Any(x => x.Equals(docTypeAlias)); 

if(!doAnyMatch) return; 
0

我想你可以用這個來代替,如果我理解得很好

loadedObj.Settings.Find(delegate(String currentCheckBox) 
{ 
    return sender.ContentType.Alias == currentCheckBox 
}); 

如果發現有問題,將返回string,如果不是null