noctonura
noctonura

Reputation: 13133

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

Upvotes: 6

Views: 13843

Answers (4)

Ed Swangren
Ed Swangren

Reputation: 124790

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

Upvotes: 2

LukeH
LukeH

Reputation: 269628

A non-LINQ alternative:

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

Upvotes: 4

recursive
recursive

Reputation: 86154

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.

Upvotes: 16

Ahmad Mageed
Ahmad Mageed

Reputation: 96557

Try:

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

Upvotes: 8

Related Questions