C# Linq

本文详细介绍了C# Linq的各种用法,包括查询、索引查询、类型筛选、复合from查询、分组查询、连接查询、Intersect操作、Zip合并、分区(分页)、聚合操作符、转换以及并行查询。通过实例展示了如何使用Linq处理学生和教师数据,涵盖了从基础查询到复杂操作的多个层面。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


前言

记录学习成果,以便温故而知新

准备工作

两个类

	/// <summary>
    /// 学生
    /// </summary>
    [Serializable]
    class Student
    {
        public string Name { get; set; }
        public string OtherName { get; set; }
        public string[] Course { get; set; }
        public string Dynasty { get; set; }

        public Student(string name, string otherName, string[] course, string dynasty)
        {
            this.Name = name;
            this.OtherName = otherName;
            this.Course = course;
            this.Dynasty = dynasty;
        }
    }
    
    /// <summary>
    /// 教师
    /// </summary>
    [Serializable]
    class Teacher
    {
        public string Name { get; set; }
        public string OtherName { get; set; }
        public string[] Course { get; set; }
        public string Dynasty { get; set; }

        public Teacher(string name, string otherName, string[] course, string dynasty)
        {
            this.Name = name;
            this.OtherName = otherName;
            this.Course = course;
            this.Dynasty = dynasty;
        }
    }    

数据

		public static List<Student> studentList = new List<Student>
        {
            new Student("颜回", "子渊", new string[]{ "诗", "书", "礼", "易", "乐", "春秋" }, "春秋"),
            new Student("闵损", "子骞", new string[]{ "诗", "书", "礼", "易", "乐", "春秋" }, "春秋"),
            new Student("冉耕", "伯牛", new string[]{ "诗", "书", "礼", "易", "乐", "春秋" }, "春秋"),
            new Student("冉雍", "仲弓", new string[]{ "诗", "书", "礼", "易", "乐", "春秋" }, "春秋"),
            new Student("冉求", "子有", new string[]{ "诗", "书", "礼", "易", "乐", "春秋" }, "春秋"),
            new Student("仲由", "子路", new string[]{ "诗", "书", "礼", "易", "乐", "春秋" }, "春秋"),
            new Student("宰予", "子我", new string[]{ "诗", "书", "礼", "易", "乐", "春秋" }, "春秋"),
            new Student("端木赐", "子贡", new string[]{ "诗", "书", "礼", "易", "乐", "春秋" }, "春秋"),
            new Student("万章", "", new string[]{ "梁惠王","公孙丑","滕文公","离娄","万章","告子","尽心" }, "战国"),
            new Student("公孙丑", "", new string[]{ "梁惠王","公孙丑","滕文公","离娄","万章","告子","尽心" }, "战国")
        };

        public static List<Teacher> teacherList = new List<Teacher>
        {
            new Teacher("孔丘", "仲尼", new string[]{ "诗", "书", "礼", "易", "乐", "春秋" }, "春秋"),
            new Teacher("孟轲", "子舆", new string[]{ "梁惠王","公孙丑","滕文公","离娄","万章","告子","尽心" }, "战国")
        };

1.查询

		/// <summary>
        /// 查询
        /// </summary>
        public static void LinqQuery()
        {
            Debug.WriteLine("------------------", "查询");

            var query = from s in studentList
                        where s.Course.Length == 6
                        select s;

            foreach (var student in query)
            {
                Debug.WriteLine("学生:" + student.Name + ",字:" + student.OtherName);
            }

            Debug.WriteLine("~~~~~~~~~~~~~~~~~~", "查询");
        }

2.索引查询

		/// <summary>
        /// 索引查询
        /// </summary>
		public static void LinqIndexQuery()
        {
            Debug.WriteLine("------------------", "索引查询");

            var query = studentList.
                Where((s, index) => s.OtherName.StartsWith("子") && index % 2 != 0);

            foreach (var student in query)
            {
                Debug.WriteLine("学生:" + student.Name + ",字:" + student.OtherName);
            }

            Debug.WriteLine("~~~~~~~~~~~~~~~~~~", "索引查询");
        }

3.类型筛选

		/// <summary>
        /// 类型筛选
        /// </summary>
        public static void LinqQueryOfType()
        {
            Debug.WriteLine("------------------", "类型筛选");

            object[] data = { "One", 2, 3, "Four", "Five", 6 };
            var query = data.OfType<int>();

            foreach (int s in query)
            {
                Debug.WriteLine(s);
            }

            Debug.WriteLine("~~~~~~~~~~~~~~~~~~", "类型筛选");
        }

4.复合from查询

		/// <summary>
        /// 复合from查询
        /// </summary>
        public static void LinqCompositeFromQuery()
        {
            Debug.WriteLine("------------------", "复合from查询");

            string course = "诗";
            var query = from s in studentList
                        from c in s.Course
                        where c == course
                        orderby s.Name descending
                        select new
                        {
                            Content = s.Name + "学习" + c
                        };

            foreach (var item in query)
            {
                Debug.WriteLine(item.Content);
            }
            course = "梁惠王";
            foreach (var item in query)
            {
                Debug.WriteLine(item.Content);
            }

            Debug.WriteLine("~~~~~~~~~~~~~~~~~~", "复合from查询");
        }

5.分组查询

		/// <summary>
        /// 分组查询
        /// </summary>
        public static void LinqGroupQuery()
        {
            Debug.WriteLine("------------------", "分组查询");

            var query = from s in studentList
                        group s by s.Dynasty into d
                        orderby d.Count() descending, d.Key
                        select new
                        {
                            Dynasty = d.Key,
                            Count = d.Count(),
                            Student = from s1 in d
                                      select "学生:" + s1.Name + ",字:" + s1.OtherName
                        };

            foreach (var dynasty in query)
            {
                Debug.WriteLine(dynasty.Dynasty + ":" + dynasty.Count);
                foreach (var s in dynasty.Student)
                {
                    Debug.WriteLine(s);
                }
            }

            Debug.WriteLine("~~~~~~~~~~~~~~~~~~", "分组查询");
        }

6.连接查询1

		/// <summary>
        /// 连接查询1
        /// </summary>
        public static void LinqJoinQuery1()
        {
            Debug.WriteLine("------------------", "分组查询1");

            var students = from s in studentList
                           from c in s.Course
                           select new
                           {
                               Course = c,
                               Student = "学生:" + s.Name + ",字:" + s.OtherName
                           };

            var teachers = from t in teacherList
                           from c in t.Course
                           select new
                           {
                               Course = c,
                               Teacher = "老师:" + t.Name + ",字:" + t.OtherName
                           };

            var studentAndTeacher = from s in students
                                    join t in teachers
                                    on s.Course equals t.Course
                                    select new
                                    {
                                        Teacher = t.Teacher,
                                        Student = s.Student,
                                        Course = s.Course
                                    };

            foreach (var item in studentAndTeacher)
            {
                Debug.WriteLine(item.Teacher + "教" + item.Student + "课程《" + item.Course + "》");
            }

            Debug.WriteLine("~~~~~~~~~~~~~~~~~~", "分组查询1");
        }

7.连接查询2

		/// <summary>
        /// 连接查询2
        /// </summary>
        public static void LinqJoinQuery2()
        {
            Debug.WriteLine("------------------", "分组查询2");

            var studentAndTeacher = from s in
                                        from s1 in studentList
                                        from c in s1.Course
                                        select new
                                        {
                                            Course = c,
                                            Student = "学生:" + s1.Name + ",字:" + s1.OtherName
                                        }
                                    join t in
                                        from t1 in teacherList
                                        from c in t1.Course
                                        select new
                                        {
                                            Course = c,
                                            Teacher = "老师:" + t1.Name + ",字:" + t1.OtherName
                                        }
                                    on s.Course equals t.Course
                                    select new
                                    {
                                        Teacher = t.Teacher,
                                        Student = s.Student,
                                        Course = s.Course
                                    };

            foreach (var item in studentAndTeacher)
            {
                Debug.WriteLine(item.Teacher + "教" + item.Student + "课程《" + item.Course + "》");
            }

            Debug.WriteLine("~~~~~~~~~~~~~~~~~~", "分组查询2");
        }

8.Intersect

		/// <summary>
        /// Intersect
        /// </summary>
        public static void LinqIntersectQuery()
        {
            Debug.WriteLine("------------------", "Intersect");

            Func<string, IEnumerable<Student>> queryStudent =
                course => from s in studentList
                          from c in s.Course
                          where c == course
                          select s;

            foreach (var student in queryStudent("春秋").Intersect(queryStudent("诗")))
            {
                Debug.WriteLine("学生:" + student.Name + ",字:" + student.OtherName);
            }

            Debug.WriteLine("~~~~~~~~~~~~~~~~~~", "Intersect");
        }

9.合并Zip

		/// <summary>
        /// 合并Zip
        /// </summary>
        public static void LinqZipQuery()
        {
            Debug.WriteLine("------------------", "Zip");

            var students = from s in studentList
                           where s.Dynasty == "春秋"
                           select s;

            var teachers = from t in teacherList
                           where t.Dynasty == "春秋"
                           select t;

            var studentAndTeacher = students.Zip(teachers, (s, t) => t.Name + "教" + s.Name);

            foreach(var item in studentAndTeacher)
            {
                Debug.WriteLine(item);
            }

            Debug.WriteLine("~~~~~~~~~~~~~~~~~~", "Zip");
        }

10.分区(分页)

		/// <summary>
        /// 分区
        /// </summary>
        public static void LinqSkipAndTakeQuery()
        {
            Debug.WriteLine("------------------", "分区");

            int pageSize = 5;
            int pages = studentList.Count / pageSize + (studentList.Count % pageSize == 0 ? 0 : 1);

            for(int page = 0; page < pages; page++)
            {
                Debug.WriteLine("第" + (page+1) + "页");
                var query = (from s in studentList
                             select s).Skip(pageSize * page).Take(pageSize);
                foreach(var student in query)
                {
                    Debug.WriteLine("学生:" + student.Name + ",字:" + student.OtherName);
                }
            }

            Debug.WriteLine("~~~~~~~~~~~~~~~~~~", "分区");
        }

11.聚合操作符

		/// <summary>
        /// 聚合操作符
        /// </summary>
        public static void LinqAggregateQuery()
        {
            Debug.WriteLine("------------------", "聚合操作符");

            var query = from s in studentList
                        group s by s.Dynasty into d
                        select new
                        {
                            Dynasty = d.Key,
                            Count = d.Count(),
                            Max = (from s1 in d select s1.Name).Max(),
                            Min = (from s1 in d select s1.Name).Min()
                        };

            foreach(var s in query)
            {
                Debug.WriteLine(s.Dynasty + " Count:" + s.Count + ",Max:" + s.Max + ",Min:" + s.Min);
            }

            Debug.WriteLine("~~~~~~~~~~~~~~~~~~", "聚合操作符");
        }

12.转换

		/// <summary>
        /// 转换
        /// </summary>
        public static void LinqToQuery()
        {
            Debug.WriteLine("------------------", "转换");

            var query = (from s in studentList
                        select s).ToList();

            foreach (var student in query)
            {
                Debug.WriteLine("学生:" + student.Name + ",字:" + student.OtherName);
            }

            var query1 = (from s in studentList
                          select s).ToLookup(s=>s.Dynasty, s=>s);

            foreach(var item in query1)
            {
                Debug.WriteLine(item.Key);
                Debug.WriteLine(item.Count());
                for(int i = 0; i < item.Count(); i++)
                {
                    Debug.WriteLine("学生:" + item.ElementAt(i).Name + ",字:" + item.ElementAt(i).OtherName);
                }
            }

            Debug.WriteLine("~~~~~~~~~~~~~~~~~~", "转换");
        }

13.并行查询

		/// <summary>
        /// 并行查询
        /// </summary>
        public static void LinqParallelQuery()
        {
            Debug.WriteLine("------------------", "并行查询");

            const int arraySize = 100000000;
            int[] data = new int[arraySize];
            var r = new Random();
            for(int i = 0; i < arraySize; i++)
            {
                data[i] = r.Next(40);
            }

            var sum = (from d in data
                       where d < 20
                       select d).Sum();
            Debug.WriteLine("Sum:" + sum);

            Debug.WriteLine("~~~~~~~~~~~~~~~~~~", "并行查询");
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值