什么是等效的lambda?

时间:2013-03-22 11:25:17

标签: c# python linq lambda

我试图使用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?

2 个答案:

答案 0 :(得分: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) 

答案 1 :(得分: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));
  }
}