改进此代码:List.Contains Regex而不创建新的比较对象?

时间:2013-04-14 23:15:16

标签: c# refactoring

我抛弃了这段代码,在LinqPad中实现了List.Contains()的Regex变种。不幸的是,强制一个人创建一个对象来进行比较,当然静态类不能实现接口。有没有办法在不创建单独的对象的情况下实现相同的结果?

void Main()
{
    var a = new List<string>();
    a.Add(" Monday ");
    a.Add(" Tuesday ");
    a.Add(" Wednesday ");
    a.Add(" Thursday ");
    a.Add(" Friday ");

    a.Contains(@"sday\s$", new ListRegexComparer() ).Dump();
}

// Define other methods and classes here
class ListRegexComparer : IEqualityComparer<string>
{

    public bool Equals(string listitem, string regex)
    {
        return Regex.IsMatch(listitem, regex);
    }


    public int GetHashCode(string listitem)
    {
        return listitem.GetHashCode();
    }

}

编辑:

a.Any(s => Regex.IsMatch(s, @"(?i)sday\s$")).Dump()

尼斯,在线方式,没有创建对象来做Chris Chavares和Jean Hominal。

1 个答案:

答案 0 :(得分:2)

Regex matcher = new Regex(@"sday\s$");
a.Any(s => matcher.IsMatch(s)).Dump();

虽然我认为你的意思是一个不同的列表方法 - according to the docs但List.Contains方法不需要比较器。

如果您不想使用Linq,那么a.Exists将使用直接在List上的方法执行相同的操作。