1

我正在尝试使用 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 的等价物?

4

2 回答 2

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

功能:

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) 
于 2013-03-22T11:32:54.043 回答
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));
  }
}
于 2013-03-22T11:30:11.780 回答