tags:

views:

214

answers:

4

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 in the compare is important.

+6  A: 

Try:

return services.Any(s =>
            s.Equals(serviceName, StringComparison.InvariantCultureIgnoreCase));
Ahmad Mageed
Great minds, great minds. Right down to the line break.
recursive
@recursive: yep, I saw that horizontal scrollbar and the rest is history :)
Ahmad Mageed
+10  A: 

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.

recursive
+2  A: 

A non-LINQ alternative:

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

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

Ed Swangren
Ya ya good point but I am interested in learning the language features as well :).
RichAmberale