2011-01-21 20 views
1

考慮以下代碼是否可以使用循環向每個唯​​一計算機添加通用服務。使用循環從列表中獲取唯一值然後添加另一個值

internal static List<MyClass> Mc = new List<MyClass>(); 

public class MyClass : OtherClass 
    { 
     public string Machine { get; set; } 
     public string Service { get; set; } 

     public void AddProcessDetails() 
     { 
      Mc.Add(new MyClass { Machine = server1, Service = "notepad" }); 
      Mc.Add(new MyClass { Machine = server2, Service = "notepad" }); 
      Mc.Add(new MyClass { Machine = server2, Service = "foo" }); 
     } 

所以,如果有一個名爲「巴」的共同服務,我怎麼能循環徹底這份名單中,讓每一個獨特的機器名然後添加機器名和服務列表?

+0

你有GetXX方法,增加了一個靜態列表?更好地修正錯誤(Mc/Md)並完成示例:應該發生什麼? – 2011-01-21 17:39:03

+0

你說的對,謝謝。 – Ryan 2011-01-21 17:54:36

回答

5

你可以使用一些LINQ:

var query = Mc.Select(m => m.Machine).Distinct().ToArray(); 
foreach (string m in query) 
    Mc.Add(new MyClass { Machine = m, Service = "bar" }); 

另外,還可以添加其他Select新對象項目,然後通過添加List.AddRange他們:

var query = Mc.Select(m => m.Machine) 
       .Distinct() 
       .Select(m => new MyClass { Machine = m, Service = "bar" }) 
       .ToArray(); 
Mc.AddRange(query); 

通常查詢是針對另一個來源,但在此c由於我們查詢的是同一個列表,因此您需要立即執行查詢,通過使用ToArray()ToList(),而不是LINQ通常的延遲(懶惰)執行。否則,您將遇到InvalidOperationException,因爲集合正在查詢並且查詢源也正在被修改。

3

它可以幫助..

var result = list.Select(x=>x.Service).Distinct(); 
forearch(MyClass cls in result) 
{ 
    collection_of_myclass.add(cls); 
} 
0

如果您使用的是.NET 2.0那麼這會爲你工作?下面是示例代碼

protected void Page_Load(object sender, EventArgs e) 

{

Employee objEmp1 = new Employee("Rahul", "Software"); 
    Employee objEmp2 = new Employee("Rahul", "Software"); 
    Employee objEmp3 = new Employee("Rahul", "Back Office"); 
    Employee objEmp5 = new Employee("Rahul", "Back Office"); 
    Employee objEmp4 = new Employee("Rahul", "Engineer"); 
    Employee objEmp6 = new Employee("Rahul", "Engineer"); 
    Employee objEmp7 = new Employee("Rahul", "Test"); 

    List<Employee> lstEmployee = new List<Employee>(); 

    lstEmployee.Add(objEmp1); 
    lstEmployee.Add(objEmp2); 
    lstEmployee.Add(objEmp3); 
    lstEmployee.Add(objEmp4); 
    lstEmployee.Add(objEmp5); 
    lstEmployee.Add(objEmp6); 
    lstEmployee.Add(objEmp7); 

    // TO GET THE GENERIC ITEMS 
    List<Employee> lstDistinct = Distinct(lstEmployee); 
} 

public static List<Employee> Distinct(List<Employee> collection) 
{ 
    List<Employee> distinctList = new List<Employee>(); 

    foreach (Employee value in collection) 
    { 
     if (!distinctList.Exists(delegate(Employee objEmp) { return objEmp.Designation == value.Designation; })) 
     { 
      distinctList.Add(value); 
     } 
    } 

    return distinctList; 
} 
相關問題