我们可以使用通用列表而不是对象数组C#

时间:2011-04-05 16:02:19

标签: c# arrays generics generic-list

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++;
  }
}

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

6 个答案:

答案 0 :(得分:5)

您的编码风格是合理且常见的,但请注意命令式是如何实现的。你说“绕过这个循环,改变这个集合,改变这个变量”,构建你想要的机器。如果给出了选择,我更喜欢用声明性样式进行编码,让编译器为我构建机器。我倾向于写这样的程序:

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();

让编译器担心循环和变量等等;你可以专注于语义而不是机制。

答案 1 :(得分:3)

这是非常基本的东西:

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

答案 2 :(得分:1)

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

答案 3 :(得分:1)

只需替换

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++;
  }

答案 4 :(得分:1)

是的,通用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);
  }
}

答案 5 :(得分:0)

如果你想要类似的语法:

ArrayList