开发者

Linq query: does this array contain this string?

Is there a better way to do this?

    public bool IsServiceRunning(string serviceName)
    {
        string[] services =  client.AllServices();
        return (from s in services
                where s.Equals(serviceName, StringComparison.InvariantCultureIgnoreCase)
                select s).Count() > 0;
    }

The case insensitivity 开发者_如何学JAVAin the compare is important.


Use the Any linq extension method:

public bool IsServiceRunning(string serviceName)
{
    string[] services =  client.AllServices();
    return services.Any(s => 
        s.Equals(serviceName, StringComparison.InvariantCultureIgnoreCase));
}

This way as soon as a match is found, execution will stop.


Try:

return services.Any(s =>
            s.Equals(serviceName, StringComparison.InvariantCultureIgnoreCase));


A non-LINQ alternative:

public bool IsServiceRunning(string serviceName)
{
    string[] services =  client.AllServices();
    return Array.Exists(services,
        s => s.Equals(serviceName, StringComparison.InvariantCultureIgnoreCase));
}


How about this?

public bool IsServiceRunning(string serviceName)
{
    string[] services =  client.AllServices();
    foreach( string service in services )
    {
        if( service.Equals( serviceName, StringComparison.OrdinalIgnoreCase ) )
        {
            return true;
        }
    }

    return false;
}

Really, it is that simple, now get back to work solving real problems. ;)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜