如何在列表中的对象属性中添加值<>

时间:2014-12-21 02:55:35

标签: c# linq properties

还是一个初学者,所以请你和我一起露面。我希望能够在列表区分出重复值之后向我的属性添加数字值。

例如,两个用户已输入系统,他们具有相同的员工ID 001,List允许他们两个进入然后应用条件检查列表中的任何重复项,因此在这种情况下会有。现在这个条件成立,将1加到该属性,这样最后一个员工现在的员工ID为002.

我相信LINQ很可能会参与这个过程,但不确定如何解决这个问题。我知道在执行此操作之后我还必须更新我的List,以便在整个程序中维护属性状态。

在此先感谢希望一切都清楚,再次提问如何为列表中的属性添加价值<>

下面的代码段。

Employee = new Employee(employeeFirstName, employeeLastName,001); // Hard coded for sake of example. 

EmployeeList.AddEmployee(Employee);

EmployeeList Class

public static void AddEmployee(Employee employee)
{

   employees.Add(new Employee(employee.FirstName,employee.LastName,employee.EmployeeID)); 
   employees.Add(new Employee("John", "Jones", 001));    

}

public void employeeIdValidation()
{
  if (employees.Count() != employees.Select(x => new {staffId = x.EmployeeID }).Distinct().Count())
  {
     Console.WriteLine("Every Book and Category should be unique");
     // employee ID increments by 1 
     // update List

  }
  else
  {
    Console.WriteLine("No duplicate found");
  }
}

public static List<Employee> GetEmployeeList()
{
  return employees; // With the updated EmployeeID 
}

2 个答案:

答案 0 :(得分:2)

恕我直言,你应该使用Dictionary<int, Employee>(其中密钥是Id)而不是list。这将强制您在添加到集合之前更新重复记录的ID,并保存一大堆麻烦和计算。

答案 1 :(得分:1)

要在列表中查找Employees具有相同ID的内容,您可以使用此linq函数。

var result=employees.ToLookup(e => e.Id);

通过这种方式,您可以对具有相同ID的员工进行分组。然后,您可以使用与我在下面显示的相同ID来迭代每组员工:

 foreach (IGrouping<int, Employee> group in result)
 {
     //More than 2 employees with the same Id
     if (group.Count()>1)
     {
       foreach (Employee employee in group)
       {
           //Change your ids here
       }
     }         
 }

[更新1 ]: 要更改我推荐的ID,您首先会在组中迭代之前找到最大ID。

  int nextID = result.Max(e => e.Key)+1;

然后,更改第二个 foreach 周期以获得 for 周期,如下所示。当您找到一个具有两个具有相同ID的Employe的组时,请不要更改第一个元素,以这种方式更改其余元素:

//The first element don't change the id, start for the second element
for (int j = 1; j < group.Count(); j++)
{
   var currentEmployee=group.ElementAt(j);
   // Change the id and refresh the nextID variable
   currentEmployee.Id = nextID++;
}
相关问题