6

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.

7
  • 1
    How that is more clear than a simple foreach loop is beyond me. Commented Jan 20, 2010 at 0:03
  • 1
    I think the proposed solutions are equally clear to a foreach loop. Commented Jan 20, 2010 at 17:39
  • I don't, but to each their own I suppose. Commented Jan 21, 2010 at 0:51
  • I believe that foreach is not the same as above because linq statement will be converted to sql that doesn't return each service (because it contains where clause). Using foreach, you return everything (i.e. select *) then you iterate over each record. That is ofc, very different. In this particular example its not important becuase AllServices already selects all records but if it returned query it would not be the same. Commented Mar 4, 2010 at 14:05
  • 1
    @majkinetor: There is no database involved in this code at all. Why are you talking about sql? Commented Oct 7, 2014 at 21:56

4 Answers 4

16

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.

Sign up to request clarification or add additional context in comments.

Comments

8

Try:

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

1 Comment

@recursive: yep, I saw that horizontal scrollbar and the rest is history :)
4

A non-LINQ alternative:

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

Comments

2

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

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.