2013-03-22 130 views
1

我試圖使用lambda的效仿以下Python代碼:什麼是等效的lambda?

checkName = lambda list, func: func([re.search(x, name, re.I) for x in list]) 

if checkName(["(pdtv|hdtv|dsr|tvrip).(xvid|x264)"], all) and not checkName(["(720|1080)[pi]"], all): 
    return "SDTV" 
elif checkName(["720p", "hdtv", "x264"], all) or checkName(["hr.ws.pdtv.x264"], any): 
    return "HDTV" 
else: 
    return Quality.UNKNOWN 

我已經創造了長格式下面的C#代碼,但我相信它可以使用lambda表達式縮短:

if (CheckName(new List<string> { "(pdtv|hdtv|dsr|tvrip).(xvid|x264)" }, fileName, true) == true & 
    CheckName(new List<string> { "(720|1080)[pi]" }, fileName, true) == false) 
{ 
    Quality = Global.EpisodeQuality.SdTv; 
} 

private bool CheckName(List<string> evals, string name, bool all) 
{ 
    if (all == true) 
    { 
    foreach (string eval in evals) 
    { 
     Regex regex = new Regex(eval, RegexOptions.IgnoreCase); 
     if (regex.Match(name).Success == false) 
     { 
     return false; 
     } 
    } 

    return true; 
    } 
    else 
    // any 
    { 
    foreach (string eval in evals) 
    { 
     Regex regex = new Regex(eval, RegexOptions.IgnoreCase); 
     if (regex.Match(name).Success == true) 
     { 
     return true; 
     } 
    } 
    return false; 
    } 
} 

任何幫助將不勝感激提高我的理解!我相信有一個更簡單/更簡單的方法!

所以經過一些更多的上場我把它簡化爲:

private static bool CheckName(List<string> evals, 
          string name, 
          bool all) 
    { 

     if (all == true) 
     { 
      return evals.All(n => 
      { 
       return Regex.IsMatch(name, n, RegexOptions.IgnoreCase); 
      }); 
     } 
     else 
     // any 
     { 
      return evals.Any(n => 
      { 
       return Regex.IsMatch(name, n, RegexOptions.IgnoreCase); 
      }); 
     } 
    } 

但一定要使用Func鍵像Python代碼當量?

+1

請記住,如果'evals'是空'All'將返回true。 – 2013-03-22 11:54:32

回答

1

事情是這樣的:

private bool CheckName(List<string> evals, string name, bool all) 
{ 
    return all ? !evals.Any(x => !Regex.IsMatch(name, x, RegexOptions.IgnoreCase)) 
       : evals.Any(x => Regex.IsMatch(name, x, RegexOptions.IgnoreCase)); 
} 

FUNC:

List<string> list = new List<string>(); 

Func<string, bool, bool> checkName = (name, all) => all 
    ? !list.Any(x => !Regex.IsMatch(name, x, RegexOptions.IgnoreCase)) 
    : list.Any(x => Regex.IsMatch(name, x, RegexOptions.IgnoreCase)); 

checkName("filename", true) 
+0

我想我想要的方式是使用Func? – user2198959 2013-03-22 11:34:47

+0

而且它似乎沒有工作 – user2198959 2013-03-22 11:40:30

+0

更新,我不得不重新閱讀這個問題(其晚):) – 2013-03-22 11:51:50

0
private bool CheckName(string eval, string name) 
{ 
    return new Regex(eval, RegexOptions.IgnoreCase).Match(name).Success; 
} 

private bool CheckName(List<string> evals, string name, bool all) 
{ 
    if (all == true) 
    { 
    return !evals.Any(eval => !CheckName(eval, name)); 
    } 
    else 
    { 
    return evals.Any(eval => CheckName(eval, name)); 
    } 
} 
相關問題