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.
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.
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.
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.
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With