• 第5章 LINQ


    5.4 LINQ查询运算符

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Collections;
    using System.IO;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                
                List<Person> list = new List<Person>();
                list.Add(new Person() { Name = "Tim Duncan", Age = 40 ,Bir=DateTime.Parse("1976-01-01 10:10:10")});
                list.Add(new Person() { Name = "Tracy McGrady", Age = 37, Bir = DateTime.Parse("1980-01-01 10:10:10") });
                list.Add(new Person() { Name = "LeBron James", Age = 31, Bir = DateTime.Parse("1984-01-01 10:10:10") });
                list.Add(new Person() { Name = "Kobe Bryant", Age = 37, Bir = DateTime.Parse("1979-01-01 10:10:10") });
    
                ArrayList arrayList = new ArrayList();
                arrayList.Add(100);
                arrayList.Add(DateTime.Now);
                arrayList.Add("Have fun");
                arrayList.Add("Interesting");
    
                //1.Where() 基于顺序号index筛选
                List<Person> query1 = list.Where((x, index) => index >= 0 && index <= 2).ToList();
    
                //2.OfType() 定义在非泛型IEnumerable上,它的作用是从非泛型集合中筛选出某一类型的成员并返回IEnumerable<T>。
                List<string> query2 = arrayList.OfType<string>().Where(_ => _.StartsWith("Have")).ToList();
    
                //3.Cast() 与OfType()类似,Cast()也定义在IEnumerable上,它用于将非泛型的序列转换为泛型序列IEnumerable<T>。当某一序列项无法成功转换时,则会抛出异常:
                //List<string> query3 = arrayList.Cast<string>().ToList();//异常,指定的转换无效
    
                //4.OrderBy()、ThenBy()、OrderByDescending()和ThenByDescending()
                List<Person> query4 = list.OrderBy(_ => _.Name).ToList();
                List<Person> query5 = list.OrderBy(_ => _.Bir.DayOfWeek).ToList();
                List<Person> query6 = list.OrderBy(_ => _.Name).ThenByDescending(_ => _.Age).ToList();
    
                //5.Select()
                List<SelectedItem> query7 = list.Select(_ => new SelectedItem() { Name = _.Name }).ToList();
    
                //6.Take()和Skip()
                List<Person> query8 = list.Take(2).ToList();
                List<Person> query9 = list.Skip(2).ToList();
    
                //7.TakeWhile()和SkipWhile()
                int[] array = { 1, 2, 10, 5, 7 };
                //array = array.TakeWhile(_ => _ <= 5).ToArray();
                //array = array.SkipWhile(_ => _ <= 5).ToArray();
    
                //8.Reverse()
                array = array.Reverse().ToArray();
    
                //9.DefaultIfEmpty()
                int[] array1 = { };
                //array1 = array1.DefaultIfEmpty(0).ToArray();
                array1 = array1.DefaultIfEmpty(100).ToArray();
                //注意到int是结构类型(值类型),它的默认值为0。当为类类型时,默认值为null,此时如果不指定默认值则会抛出异常:未将对象引用设置到对象的实例。
                List<Person> list1 = new List<Person>();
                List<Person> list2 = list1.DefaultIfEmpty().ToList();
                //list2.ToArray()[0].ToString();//异常
    
                //10.Distinct() 传递一个IEqualityComparer<T>类型,它包含了对象比较的算法
                List<Person> query10 = list.Distinct(new PointComparer()).ToList();
    
                //11.GroupBy()
                List<IGrouping<int, Person>> query11 = list.GroupBy(_ => _.Age).ToList();
                foreach (var item in query11)
                {
                    foreach (var person in item)
                    {
                        Console.WriteLine(person.Name);
                    }
                }
    
                //12.Intersect()和Except()
                int[] array2 = { 0, 1, 2 };
                int[] array3 = { 2, 3, 4 };
                int[] query12 = array2.Intersect(array3).ToArray(); // 得到 2
    
                Person[] array4 = { new Person() { Name = "Tracy McGrady", Age = 37 } };
                Person[] array5 = { new Person() { Name = "Kobe Bryant", Age = 37 } };
                List<Person> query13 = array4.Intersect(array5, new PointComparer()).ToList();
    
                query12 = array2.Except(array3).ToArray(); // 得到 2
    
                //13.Concat()和Union()
                //query12 = array2.Concat(array3).ToArray();
                query12 = array2.Union(array3).ToArray();
    
                //14.Zip()
                int[] array6 = { 1, 2, 3, 4, 5 };
                string[] array7 = { "星期一", "星期二", "星期三" };
                string[] array8 = array6.Zip(array7, (x, y) => string.Format("{0},{1}", x, y)).ToArray();
    
                //15.ElementAt()和ElementAtOrDefault()
                //16.First()和FirstOrDefault()
                //17.Last()和LastOrDefault()
                //18.Single()和SingleOrDefault()
                //19.Count()和LongCount()
                //20.Max()、Min()、Average()和Sum()
                //21.Aggregate()
                int[] array9 = { 1, 2, 3 };
                int sum = array9.Aggregate(0, (total, x) => total + (x * 2));
                Console.WriteLine(sum);
    
                //22.Contains()、Any()、All()和SequenceEqual()
                Console.Read();
            }
        }
    
        public class PointComparer : IEqualityComparer<Person>
        {
    
            public bool Equals(Person x, Person y)
            {
                return x.Age == y.Age;
            }
    
            public int GetHashCode(Person obj)
            {
                return obj.Age;
            }
        }
    
        public class Person
        {
            public string Name { get; set; }
            public int Age { get; set; }
            public DateTime Bir { get; set; }
        }
    
        public class SelectedItem
        {
            public string Name { get; set; }
        }
    }
  • 相关阅读:
    2018-9-28-WPF-自定义-TextBoxView-的-Margin-大小
    2018-6-24-WPF-使用RPC调用其他进程
    2018-6-24-WPF-使用RPC调用其他进程
    2019-9-2-通过命令行使用微信
    2019-9-2-通过命令行使用微信
    2019-9-2-git-需要知道的1000个问题
    2019-9-2-git-需要知道的1000个问题
    pip install 安装出现问题:UnicodeEncodeError: 'ascii' codec can't encode characters in position XX的解决办法
    Java 使用Redis缓存工具的图文详细方法
    0基础学编程,我想给你这 5 个建议
  • 原文地址:https://www.cnblogs.com/liuslayer/p/5455565.html
Copyright © 2020-2023  润新知