C# 使用字典变量上的循环

C# 使用字典变量上的循环,c#,C#,我使用dictionary变量并在其中添加所有服务名称,并调用foreach循环来迭代系统并获取所有服务 我使用List使用了这段代码,它工作得非常好,现在我使用Dictionary变量,无法循环所有服务 foreach(ServiceController service in ServiceController.GetServices()) { string serviceName = service.ServiceName; string serviceDisplayName = s

我使用dictionary变量并在其中添加所有服务名称,并调用foreach循环来迭代系统并获取所有服务

我使用List使用了这段代码,它工作得非常好,现在我使用Dictionary变量,无法循环所有服务

foreach(ServiceController service in ServiceController.GetServices()) {
  string serviceName = service.ServiceName;
  string serviceDisplayName = service.DisplayName;
  string serviceType = service.ServiceType.ToString();
  string status = service.Status.ToString();

  Dictionary<int, string> output = new Dictionary<int, string>();

  if (service.Status == ServiceControllerStatus.Running) {
    string exists = null; {
      output.Add(1, "RUNNING SERVICE: ");
      output.Add(2, "Service Name: " + serviceName);
      output.Add(3, "Service Display Name: " + serviceDisplayName);
      output.Add(4, "Service Type: " + serviceType);
      output.Add(5, "Service Status: " + status);

      if (output.ContainsKey(1) == true) {
        exists = (output[1]);
      }
      if (output.ContainsKey(2) == true) {
        exists = (output[2]);
      }
      if (output.ContainsKey(3) == true) {
        exists = (output[3]);
      }
      if (output.ContainsKey(4) == true) {
        exists = (output[4]);
      }
      if (output.ContainsKey(5) == true) {
        exists = (output[5]);
      }

    }
  } else {}

  foreach(var i in output) {
    var result = string.Join(Environment.NewLine, output);
    Result.Set(context, result);
  }
}

现在这段代码给了我这个输出。这只是一个服务信息,我需要系统中存在的所有服务。

什么是
ServiceController.GetServices().Count()
?您是否觉得单条目是最后一个运行的服务(请注意,它以Z开头)有点奇怪?这会告诉你什么?你在循环中创建了字典实例,这样你就只得到字典中的最后一个服务(所有以前的服务循环迭代都被丢弃)你能发布代码吗?你是如何打印结果的,看起来你有这个上下文对象,您正在将所有日志添加到某种映射中。@Theodorzouli,因为OP需要多条记录。由于如何调用
Result.Set
,他/她现在只得到一个(最后一个)。@mjwills我不知道
Result.Set()
做什么。我假设它是某种
控制台。WriteLine
。我想说,整个代码令人难以置信。什么是
ServiceController.GetServices().Count()
?您是否觉得单条目是最后一个运行的服务(请注意,它以Z开头)有点奇怪?这会告诉你什么?你在循环中创建了字典实例,这样你就只得到字典中的最后一个服务(所有以前的服务循环迭代都被丢弃)你能发布代码吗?你是如何打印结果的,看起来你有这个上下文对象,您正在将所有日志添加到某种映射中。@Theodorzouli,因为OP需要多条记录。由于如何调用
Result.Set
,他/她现在只得到一个(最后一个)。@mjwills我不知道
Result.Set()
做什么。我假设它是某种
控制台。WriteLine
。我要说的是,整个代码令人难以置信。
[1, RUNNING SERVICE: ]
[2, Service Name: ZAtheros Bt and Wlan Coex Agent]
[3, Service Display Name: ZAtheros Bt and Wlan Coex Agent]
[4, Service Type: Win32OwnProcess]
[5, Service Status: Running]