Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq query: does this array contain this string?

Tags:

c#

linq

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.

like image 528
noctonura Avatar asked Jan 19 '10 23:01

noctonura


People also ask

How to check contains in LINQ?

The Linq Contains Method in C# is used to check whether a sequence or collection (i.e. data source) contains a specified element or not. If the data source contains the specified element, then it returns true else return false.

How use contains in LINQ query?

All, Any & Contains are quantifier operators in LINQ. All checks if all the elements in a sequence satisfies the specified condition. Any check if any of the elements in a sequence satisfies the specified condition. Contains operator checks whether specified element exists in the collection or not.

What is LINQ in C# with example?

LINQ is the basic C#. It is utilized to recover information from various kinds of sources, for example, XML, docs, collections, ADO.Net DataSet, Web Service, MS SQL Server, and different database servers.


3 Answers

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.

like image 144
recursive Avatar answered Oct 15 '22 13:10

recursive


Try:

return services.Any(s =>
            s.Equals(serviceName, StringComparison.InvariantCultureIgnoreCase));
like image 32
Ahmad Mageed Avatar answered Oct 15 '22 12:10

Ahmad Mageed


A non-LINQ alternative:

public bool IsServiceRunning(string serviceName)
{
    string[] services =  client.AllServices();
    return Array.Exists(services,
        s => s.Equals(serviceName, StringComparison.InvariantCultureIgnoreCase));
}
like image 22
LukeH Avatar answered Oct 15 '22 13:10

LukeH