使用循环从列表中获取唯一值,然后添加另一个值

时间:2011-01-21 17:32:17

标签: c# generics collections loops c#-4.0

考虑以下代码,可以使用循环为每个唯一的计算机添加公共服务。

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" });
        }

因此,如果有一个名为“bar”的公共服务,我该如何遍历此列表,获取每个唯一的计算机名称,然后将该计算机名称和服务添加到列表中?

3 个答案:

答案 0 :(得分: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);

通常查询针对另一个源,但在这种情况下,因为我们查询相同的列表,您需要使用ToArray()ToList()立即执行查询,而不是LINQ通常的延迟(懒惰)执行。否则,您将遇到InvalidOperationException,因为集合正在查询,并且查询源也正在被修改。

答案 1 :(得分:3)

这可能会有所帮助..

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

答案 2 :(得分: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;
}