我们可以使用通用列表而不是对象数组 C#
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++;
}
}
这里我不知道数组长度。需要它动态取决于总条件是否真实。有没有使用通用列表执行相同操作的有效方法?如果是这样,该怎么做?
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++;
}
}
Here I don't know the array length. Need it dynamic depending on the total conditions are true. Is there any efficient way of doing the same using Generic List? If so, how to do so?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您的编码风格是合理且常见的,但请注意它的重要性。你说的是“绕过这个循环,改变这个集合,改变这个变量”,构建一个能做你想要的事情的机器。当有选择时,我更喜欢以声明式风格进行编码,并让编译器为我构建机器。我倾向于这样编写你的程序:
让编译器担心循环和变量等等;您可以专注于语义而不是机制。
Your coding style is reasonable and common, but notice how imperative it is. You're saying "go around this loop, mutate this collection, change this variable", building the machine that does what you want. When given the choice I prefer to code in a declarative style, and let the compiler build the machine for me. I would be inclined to write your program like this:
Let the compiler worry about the loops and variables and whatnot; you can concentrate on the semantics rather than the mechanisms.
这是非常基本的东西:
This is really basic stuff:
只需将
:
循环替换为
Just replace
with
and the loop with:
是的,通用的
List
在这里会很好用。Yes a generic
List<Student>
will work great here.如果您想要类似的语法:
ArrayList
If you want a similar syntax :
ArrayList