等价的是什么?

本文关键字:是什么 | 更新日期: 2023-09-27 18:05:12

我正在尝试使用lambda来模拟以下python代码:

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);
            });
        }
    }

但是必须像python代码一样使用Func吗?

等价的是什么?

像这样:

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) 
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));
  }
}