Linq练习

准备类以及数据 

class Student
{
    public int StudentId { get; set; }
    public string Name { get; set; }
    public Course Course { get; set; }

    public Student(int studentId, string name, Course course)
    {
        StudentId = studentId;
        Name = name;
        Course = course;
    }

    public void PrintInfo()
    {
        Console.WriteLine("Student ID: " + StudentId);
        Console.WriteLine("Name: " + Name);
        Console.WriteLine("Current Course: " + Course.Name);
        Console.WriteLine("Course Instructor: " + Course.Instructor);
    }
}

class Course
{
    public int CourseId { get; set; }
    public string Name { get; set; }
    public string Instructor { get; set; }

    public Course(int courseId, string name, string instructor)
    {
        CourseId = courseId;
        Name = name;
        Instructor = instructor;
    }
}
 List<Student> studentList = new List<Student>()
            {
                new Student(10001, "Alice", new Course(1, "Mathematics", "John Smith")),
                new Student(10002, "Bob", new Course(2, "Computer Science", "Jane Doe")),
                new Student(10003, "Charlie", new Course(3, "History", "Susan Johnson")),
                new Student(10004, "David", new Course(1, "Mathematics", "John Smith")),
                new Student(10005, "Eva", new Course(4, "Physics", "Robert Brown")),
                new Student(10006, "Frank", new Course(5, "Biology", "Emma Wilson")),
                new Student(10007, "Grace", new Course(3, "History", "Susan Johnson")),
                new Student(10008, "Henry", new Course(6, "Chemistry", "William Garcia")),
                new Student(10009, "Ivy", new Course(7, "Music", "Olivia Davis")),
                new Student(10010, "Jack", new Course(8, "Art", "Michael Taylor"))
            };

查询名字以 "A" 开头的学生 

 var query1 = studentList.Where(s => s.Name.StartsWith("A"));

查询参加数学课程的学生 

var query2 = studentList.Where(s => s.Course.Name == "Mathematics");

查询参加数学课程的学生数量

var count = studentList.Count(s => s.Course.Name == "Mathematics");

按学生姓名进行升序排序

var query3 = studentList.OrderBy(s => s.Name);

查询参加不同课程的学生姓名列表

var query4 = studentList.Select(s => s.Name).Distinct();

查询参加数学课程的学生姓名列表

 var query5 = studentList
                .Where(s => s.Course.Name == "Mathematics")
                .Select(s => s.Name);

返回第一个参加历史课程的学生

var firstStudent = studentList.FirstOrDefault(s => s.Course.Name == "History");

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值