创建Collection集合存储 Student对象向集合中添加一组Student对象判断是否存在姓名为lisi的同学删除成绩不及格的同学foreach遍历
时间: 2023-06-16 15:06:19 浏览: 42
下面是一个示例代码,演示了如何创建一个 `List<Student>` 集合,向其中添加 `Student` 对象,判断是否存在姓名为 "lisi" 的同学,删除成绩不及格的同学,并使用 `foreach` 遍历集合中的元素:
```csharp
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
List<Student> students = new List<Student>();
// 添加一组 Student 对象
students.Add(new Student("zhangsan", 80));
students.Add(new Student("lisi", 70));
students.Add(new Student("wangwu", 90));
// 判断是否存在姓名为 "lisi" 的同学
bool existsLisi = students.Exists(s => s.Name == "lisi");
Console.WriteLine("Exists lisi: " + existsLisi);
// 删除成绩不及格的同学
students.RemoveAll(s => s.Score < 60);
// 使用 foreach 遍历集合中的元素
foreach (Student s in students)
{
Console.WriteLine("Name: {0}, Score: {1}", s.Name, s.Score);
}
}
}
class Student
{
public string Name { get; set; }
public int Score { get; set; }
public Student(string name, int score)
{
Name = name;
Score = score;
}
}
```
输出结果:
```
Exists lisi: True
Name: zhangsan, Score: 80
Name: wangwu, Score: 90
```