我们可以用泛型列表代替c#对象数组吗?

本文关键字:对象 数组 泛型 列表 我们 | 更新日期: 2023-09-27 17:49:19

class Student
{
  public string ID { get; set; }
  public string Name { get; set; }
}
Student[] students = new Student[10];
int j = 0;
for(int i=0; i < 100; i++)
{
  if (some condition)
  {
    student[j].ID = anotherIDlist[i]; //some value from another list;
    student[j].Name = anotherNamelist[i]; //some value from another list;
    j++;
  }
}

这里我不知道数组的长度。需要它动态取决于总的条件是否为真。是否有任何有效的方法来做同样的使用通用列表?如果有,如何去做?

我们可以用泛型列表代替c#对象数组吗?

您的编码风格是合理和通用的,但是请注意是多么的命令式。你在说"绕着这个循环,改变这个集合,改变这个变量",制造出你想要的机器。如果可以选择,我更喜欢使用声明式风格,让编译器为我构建机器。我倾向于这样写你的程序:

var query = from i in Enumerable.Range(0, 100)
            where some_condition
            select new Student() { Id = ids[i], Name = names[i] };
var students = query.ToList();

让编译器操心循环和变量之类的;您可以专注于语义而不是机制。

这是非常基本的东西:

var students = new List<Student>();
for(int i=0; i < 100; i++)
{
    if (some condition)
    {
        // You can produce the student to add any way you like, e.g.:
        someStudent = new Student { ID = anotherIDlist[i], Name = anotherNamelist[i] };
        students.Add(someStudent);
    }
}
List<Students> students = new List<Students>;
for(int i=0; i < 100; i++)
{
  if (some condition)
  {
    students.Add(new Student { .ID = anotherIDlist[i], .Name = anotherNamelist[i]));
  }
}

直接替换

Student[] students = new Student[10];

List<Student> students = new List<Student();

和:

的循环
  if (some condition)
  {
    Student student = new Student();
    student.ID = anotherIDlist[i]; //some value from another list;
    student.Name = anotherNamelist[i]; //some value from another list;
    students.Add(student);
    j++;
  }

是的,通用的List<Student>将在这里工作得很好。

List<Student> students = new List<Student>();
for(int i=0; i < 100; i++)
{
  if (some condition)
  {
    Student s = new Student();
    s.ID = anotherIDlist[i]; //some value from another list;
    s.Name = anotherNamelist[i]; //some value from another list;
    students.Add(s);
  }
}

如果您需要类似的语法:

ArrayList