2013-10-11 24 views
0

我必須按每個Key中的某個字符串模式過濾ResourceSet。爲此,我的函數必須接收參數a lambda表達式。我沒有經驗lambda,所以我不知道如何查詢ResourceSet中的每個DictionaryEntry將lambda作爲參數傳遞給將要查詢ResourceSet的方法

這是我目前的方法,但看起來醜陋的老:

public IDictionary<string, string> FindStrings(string resourceName, params string[] pattern) 
{ 
    OpenResource(resourceName); 

    ResourceSet resourceSet = _currentResourseManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true); 
    Dictionary<string, string> result = new Dictionary<string, string>(); 

    foreach (DictionaryEntry entry in resourceSet) 
    { 
     string resourceKey = entry.Key.ToString(); 

     foreach (string p in pattern) 
     { 
      if (resourceKey.StartsWith(p)) 
      { 
       string resource = entry.Value.ToString(); 
       result.Add(resourceKey, resource); 
      } 
     } 
    } 

    return result; 
} 

如何我Func鍵參數會看?拉姆達將如何看待?

+0

好吧,根據你的問題描述,這聽起來像你實際上不會改變你的方法 - 只是「if resourceKey.startsWith」;您需要提供一個接受字符串的Func,並返回一個布爾值(通過過濾器)。這裏是Func的文檔,如果它有幫助:http://msdn.microsoft.com/en-us/library/bb549151.aspx缺少任何東西,或者我誤解了你的需求? – Katana314

回答

2

你想通過一個謂詞這是一個函數接受一個字符串,並返回一個布爾值,指示輸入字符串是否匹配某些條件。

這裏是你實現如何看起來像:

public IDictionary<string, string> FindStrings(string resourceName, Func<string, boolean> keySelector) 
{ 
    OpenResource(resourceName); 

    ResourceSet resourceSet = _currentResourseManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true); 
    Dictionary<string, string> result = new Dictionary<string, string>(); 

    foreach (DictionaryEntry entry in resourceSet) 
    { 
     string resourceKey = entry.Key.ToString(); 

     if (keySelector(resourceKey)) 
     { 
      string resource = entry.Value.ToString(); 
      result.Add(resourceKey, resource); 
     } 

    } 

    return result; 
} 

下面是如何使用Lambda表達式調用方法:

var patterns = new string[] { "test1", "test2" }; 
var results = FindString("Resource1", key => patterns.Any(p => key.StartsWith(p))); 

更多關於代表:Delegates (C# Programming Guide) - MSDN。 有關lambda表達式的更多信息:Lambda Expressions (C# Programming Guide) - MSDN

希望這會有所幫助。