通过LINQ查询将ServiceController对象绑定到List

时间:2013-12-17 05:44:28

标签: c# linq

我有一个4弦的类。我试图使用ServiceController迭代每个Windows服务,然后将其绑定到类对象列表。

两个选项中的哪一个会更好,如何做到这两个

我的目标是将此列表绑定到Gridview作为数据源。

public class ServiceDetails
{
    public string ServiceName { get; set; }
    public string Status { get; set; }
    public string Description { get; set; }
    public string Location { get; set; }
}


protected void GetAllServices(string machinename)
{
    ServiceController[] services = ServiceController.GetServices(machinename);
    List<ServiceDetails> svcdetails = new List<ServiceDetails>();

    // option 1 - to iterate through each and bind to list
    foreach (ServiceController service in services)
    {
        //How to bind the servicecontroller object to a list.?
    }

    // option 2 - Bind the List using LINQ query
    List<ServiceDetails> items = svcdetails.ForEach(service=> LINQ Query...?

    Gridview.DataSource = items;            
    Gridview.DataBind(); 
}

1 个答案:

答案 0 :(得分:0)

请确保您已添加以下内容:

using System.Linq;

然后执行以下操作:

var items = services.Select(s=>new ServiceDetails{
 ServiceName = s.ServiceName,
 Status = s.Status,
 Description = s.Description,
 Location = s.Location
}).ToList();

我假设ServiceController类的属性名称。然后,

Gridview.DataSource = items;

执行此操作后,您必须在View / aspx页面中配置列映射