开发者

Linq query: does this array contain this string?

开发者 https://www.devze.com 2022-12-16 19:00 出处:网络
Is there a better way to do this? public bool IsServiceRunning(string serviceName) { string[] services =client.AllServices();

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

精彩评论

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