Linq练习

2024-01-10 15:52:18

准备类以及数据?

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");

文章来源:https://blog.csdn.net/weixin_54498280/article/details/135496936
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。