我正在尝试显示保存在响应数据库中的部门,而没有学生分配到某个部门。我有以下代码,错误消息正确显示但没有学生的部门列表不是。
private static void displayDepartments(University u)
{
foreach (Department d in u.Departments)
{
if (d.contains(null))
{
Console.WriteLine(d.ToString());
}
else
{
Console.WriteLine("All departments contain students");
}
}
}
答案 0 :(得分:1)
这个答案基于澄清的问题(阅读其他答案的评论)。
bool errors = false;
foreach (Department d in u.Departments)
if (d.students.Count == 0) // students is IList<> it has a property Count
{
Console.WriteLine(d.name); // name is string
errors = true;
}
if (!errors)
Console.WriteLine("All departments contain students");
根据不准确的信息做出第一个答案:
由于您的Department类是IEnumerable,您将能够执行以下操作:
bool emptyDep = true;
foreach (Department d in u.Departments)
{
if (!d.Any())
{
emptyDep = true;
Console.WriteLine(d.ToString());
}
}
if (!emptyDep)
{
Console.WriteLine("All departments contain students")
}
答案 1 :(得分:0)
这些方面应该有用......
private static void displayDepartments(University u)
{
foreach (Department d in u.Departments)
{
if (d.students.Count == 0)
{
Console.WriteLine(d.name.ToString());
}
else
{
Console.WriteLine("All departments contain students");
}
}
}