有更好的方法吗?
public bool IsServiceRunning(string serviceName)
{
string[] services = client.AllServices();
return (from s in services
where s.Equals(serviceName, StringComparison.InvariantCultureIgnoreCase)
select s).Count() > 0;
}
比较中的不区分大小写非常重要。
答案 0 :(得分:16)
使用Any
linq扩展方法:
public bool IsServiceRunning(string serviceName)
{
string[] services = client.AllServices();
return services.Any(s =>
s.Equals(serviceName, StringComparison.InvariantCultureIgnoreCase));
}
这样一旦找到匹配,执行就会停止。
答案 1 :(得分:8)
尝试:
return services.Any(s =>
s.Equals(serviceName, StringComparison.InvariantCultureIgnoreCase));
答案 2 :(得分:4)
非LINQ替代方案:
public bool IsServiceRunning(string serviceName)
{
string[] services = client.AllServices();
return Array.Exists(services,
s => s.Equals(serviceName, StringComparison.InvariantCultureIgnoreCase));
}
答案 3 :(得分:2)
这个怎么样?
public bool IsServiceRunning(string serviceName)
{
string[] services = client.AllServices();
foreach( string service in services )
{
if( service.Equals( serviceName, StringComparison.OrdinalIgnoreCase ) )
{
return true;
}
}
return false;
}
真的,就是这么简单,现在回去解决真正的问题。 ;)