列出4年内完成毕业的学生的名单,以及花费4年以上或不到4年才完成毕业的学生的名单,并通过从用户那里获得条目来打印两个列表。
我已经列出了我使用的代码也可以正常工作的列表,但是我使用了两个foreach循环来打印两个列表,但是我只想使用一个循环来减少代码的长度。下面是我用作初学者的代码。
public void Print(List<Student> students)
{
foreach (Student student in students)
{
if (student.Time == "4")
{
Console.WriteLine($"\nPeople who completed graduation in 4 years : \n{student.Name}");
}
}
foreach (Student student in students)
{
if (student.Time != "4")
{
Console.WriteLine($"\nPeople who completed graduation in more or less than 4 years : \n{student.Name}\t{student.Time}");
}
}
}
答案 0 :(得分:2)
要合并语句,仅使用一个foreach循环,请使用else。
public void Print(List students)
{
foreach (Student student in students)
{
if (student.Time =="4")
{
Console.WriteLine($"\nPeople who completed graduation in 4 years : \n{student.Name}");
}
else
{
Console.WriteLine($"\nPeople who completed graduation in more or less than 4 years : \n{student.Name}\t{student.Time}");
}
}
}
如果您在两个列表变量之后,则可以使用linq和.Where()
public void Print(List students)
{
var studentsIn4Years = students.Where(s => s.Time == "4");
var studentsNotIn4Years = students.Where(s => s.Time != "4");
// Do your logic here.
}
答案 1 :(得分:0)
我认为您正在寻找这样的东西:
public void Print(List<Student> students)
{
var studentsIn4Years = new List<string>();
var studentsNotIn4Years = new List<string>();
foreach (var student in students)
{
if (student.Time == "4")
{
studentsIn4Years.Add(student.Name);
}
else
{
studentsNotIn4Years.Add($"{student.Name}\t{student.Time}");
}
}
Console.WriteLine($"\nPeople who completed graduation in 4 years: ", string.Join(", ", studentsIn4Years));
Console.WriteLine($"\nPeople who completed graduation in more or less than 4 years: ", string.Join(", ", studentsNotIn4Years));
}
但是,如果学生人数不多,我建议您考虑简单性而不是伪优化,并使用LINQ这样实现:
public void Print2(List<Student> students)
{
var studentsIn4Years = students.Where(s => s.Time == 4).Select(s => s.Name);
var studentsNotIn4Years = students.Where(s => s.Time == 4).Select(s => $"{student.Name}\t{student.Time}");
Console.WriteLine($"\nPeople who completed graduation in 4 years: ", string.Join(", ", studentsIn4Years));
Console.WriteLine($"\nPeople who completed graduation in more or less than 4 years: ", string.Join(", ", studentsNotIn4Years));
}