【问题标题】:C# is there a better way of adding an element from a list in another class?C# 有没有更好的方法从另一个类的列表中添加元素?
【发布时间】:2021-09-05 14:28:09
【问题描述】:

这是头等舱

public class Employees
 {
    public int empID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Position { get; set; }
    public string Email { get; set; }
 }
public class list
{
    static public List<Eployees> _employees = new List<Employees>();

    public List<Employees> GetList()
    {
        return _employees;
    }

    public string fname;
    public void Add()
    {
        int result = _employees.Count(x => x.empID == x.empID);
        int id = result + 1; //auto increment for empID

         _employees.Add(new Employees
        {
            empID = id,
            FirstName = fname
        });
    }

这是第二课

class Class1
{
  public static main void Main(string[] args)
  {
 ManageEmployee();
}

 static void AddEmployees
{
list ll = new list();

Console.WriteLine("Enter FirstName ");
 string name = Console.ReadLine();
 ll.name = name;
 ll.Add();
 string view = Console.ReadLine();

 foreach(var Employees in list._employees)
 {
  Console.WriteLine(Employees.empID + " | " + Employees.FirstName);
 }
 string reset = Console.ReadLine();
 AddEmployees();
 }
}

我是 C# 新手,基本上,我想知道有没有更好的方法将元素添加到列表中?我看到我的老师做了一些不同的事情,但我不明白她是怎么做到的,我一直在寻找更好的添加方法

【问题讨论】:

  • 就个人而言,我不会命名class list。当您开始使用代码时,这会变得非常混乱,因为正如您在自己的使用中所看到的那样,您在 list 类中创建了一个 List&lt;Eployees&gt;
  • 看到AddEmployee没有定义,我会说是的,有比使用未定义方法更好的方法。

标签: c# list linq add


【解决方案1】:

首先,我会用单数形式命名持有一个员工的班级:

public class Employee
{
    public int empID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Position { get; set; }
    public string Email { get; set; }
}

然后,您的班级管理我将命名为 EmployeesManagement 的员工,并且我将强制在 Add 方法中提供名字(也许提供其他属性也是有益的):

public class EmplyoeesManagement
{
    private List<Employee> _employees = new List<Employee>();

    public List<Employee> GetList()
    {
        return _employees;
    }

    public void Add(string firstName)
    {
        _employees.Add(new Employee { empID = _employees.Select(e => e.empID).Max() + 1, FirstName = firstName });
    }
}

请注意,新员工的 ID 不是基于列表中的员工数量创建的(猜想当您从列表中删除员工时会发生什么),而是基于那里已经存在的最大值。

另外,考虑哪些属性需要是静态的和公共的。如果没有任何特殊原因,请将它们设为非静态和私有

在你的第二堂课中,我会使用字符串生成器来创建现有员工的完整列表,但这对你来说只是一个练习。

请使用缩进,这样你的代码看起来更整洁。

【讨论】:

  • 非常感谢您,我从您的回答中学到了很多东西。你的 add 方法是我一直想做的。我还在 .Max() 旁边添加了一个 .DefaultIfEmpty(),因此第一个条目不会返回错误。谢谢你的教导。
  • 我很高兴听到这个消息,我很高兴您已经在修改代码并使其更安全。这就是要走的路!
猜你喜欢
  • 1970-01-01
  • 2021-01-24
  • 2017-01-22
  • 2020-04-23
  • 1970-01-01
  • 2010-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多