• C# lambda表达式及初始化器


    using System;using System.Collections.Generic;
    using System.Linq;
    namespace ConsoleApplication1d
    {
    class CTX
        {
            public int id = 10;
            public string name = "rich";
            public int age = 28;
            public CTX(int id)
            {
                this.id = id;
            }
        }
        class Test
        {
            delegate List<int> EvenCheck(List<int> lst);
            public static void Main()
            {
                List<int> lst = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; //List初始化器
                Dictionary<int, CTX> dict = new Dictionary<int, CTX>()//Dictionary初始化器
                {
                    {1, new CTX(20) {name = "Tom" } },//对象的初始化器
                    {
                        2,
                        new CTX(0) {age = 30, id = 10020, name = "unknown" } //对象的初始化器
                    }
                };
    
                //Func<T> 系统定义的委托,参数数目可变, 至少二个参数,最后一个为返回值类型,其余为输入参数类型
                Func<int, int> fdg = p => p + 10;
                Console.WriteLine(fdg(333));//343
                Func<int, int, string> fadg = (p, q) => (p + q).ToString();
                Console.WriteLine(fadg(-10, -20));//-30
    
                EvenCheck eck = p => //委托中的lambda,相当于一个匿名函数,参数为p, 返回值为list<int>,符合EvenCheck的委托类型,因此可直接赋值
                {
                    List<int> tlst = new List<int>();
                    foreach(var e in p)
                    {
                        if (e % 2 == 0)
                            tlst.Add(e);
                    }
    
                    return tlst;
                };
    
                List<int> lst2 = lst.Where(p => p % 2 == 0).ToList(); //条件表达式中的lambda,Where参数为Func<int, int>,因此可用lambda
                List<int> lst3 = eck(lst);
                int lx = lst3.SingleOrDefault(p => p == 6); //条件表达式中的lambda
    
                lst3 = lst3.OrderBy(p => p).ToList(); //升序,OrderBy参数为Func<int, int>,因此可用lambda
                lst3 = lst3.OrderByDescending(p => p).ToList();//降序,OrderByDescending参数为Func<int, int>,因此可用lambda
                lst3.Sort();//升序
    
                foreach(var l in lst3)
                {
                    Console.Write(l +" ");
                }
                Console.WriteLine();
            }
        }
    }
  • 相关阅读:
    day22-20180522笔记
    day20-20180517笔记
    day19-20180515笔记
    day18-20180513笔记
    day17-20180510笔记
    day16-20180508笔记
    Python之初识面向对象
    Python之常用模块(2)
    Python之常用模块(1)
    Python之模块与包(下)
  • 原文地址:https://www.cnblogs.com/timeObjserver/p/5966356.html
Copyright © 2020-2023  润新知