码迷,mamicode.com
首页 > 其他好文 > 详细

Lambda表达式

时间:2020-01-10 00:40:56      阅读:75      评论:0      收藏:0      [点我收藏+]

标签:car   cat   derby   game   love   water   reac   san   getc   

自己保存一些偶尔用的到的Lambda表达式小技巧

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace Senior
{
    class Program
    {
        static void Main(string[] args)
        {
            #region Lambda表达式
            //使用lambda表达式比匿名方法更节省代码和容易理解,其实lambda表达式是使用匿名函数Rredicate<T>的标准的匿名方法而已
            TraditionDelegateSyntax();

            AnonymousMethodSyntax();

            LambdaExpressionSyntax();

            List<Car> myCars = new List<Car>()
            {
                  new Car{PetName="Henry",Color="Silver",Speed=100,Make="BMW"},
                  new Car{PetName="Daisy",Color="Tan",Speed=90,Make="BMW"},
                  new Car{PetName="Mary",Color="Black",Speed=55,Make="VW"},
                  new Car{PetName="Clunker",Color="Rust",Speed=5,Make="Yugo"},
                  new Car{PetName="Melvin",Color="White",Speed=43,Make="Ford"}
            };

            GetFastCars(myCars);  //访问包含的子对象

            LINQOverArrayList();  //将LINQ查询应用与非泛型集合

            OfTypeAsFilter(); //使用ofType<T>()筛选数据


            ProductInfo[] itemsInstock = new[]{
                new   ProductInfo { Name = " mac‘s CoffDescription", Description= "Coffee with TEETH" ,NumberInStock = 24 },
                new ProductInfo { Name = " Milk Maid Milk" ,Description = "Milk cow‘s love", NumberInStock = 100 },
                new ProductInfo { Name = " Pure Silk Tofu",Description = "Bland as Possible" ,NumberInStock = 120 },
                new  ProductInfo { Name= " Cruchy",Description = "Cheezypepperygoodness", NumberInStock = 2 } ,
                new ProductInfo{ Name = " Ripoff water " ,Description = "From the tap to your wallet",NumberInStock = 100 },
                new ProductInfo { Name ="Classic Valpo Pizza ",Description =" Everyone loves pizza " ,NumberInStock=73}
            };

            SelectEverything(itemsInstock); //获取所有的数据
            ListProductNames(itemsInstock);  //只提取产品的名字
            GetOverstock(itemsInstock);  //获取数据子集
            GetNamesAndDescriptions(itemsInstock);  //投影新数据类型,可投影需要的数据
            GetCountFromQuery();  //使用Enumberable中的Count获取总条数
            ReversetEverything(itemsInstock);//反转结果集
            AlphabetizeProductNumber(itemsInstock); //对表达式中的数量进行升序排序
            DisplayDiff();  // Except方法是返回包含两个容器不同之处的LINQ结果集,是返回第一个List中,在第二个List中没有出现过的值
            DiaplayIntersection(); //Intersect方法是返回两个容器中共同的数据
            DisplayUnion(); //Union方法返回是多个LINQ查询中的所有成员,如果相同成员出现过多次,将只能返回一个
            DisplayConcatNoDups();  //使用Concat()+foreach中调用distinct()方法,可移除重复的数据
            AggregateOps();  //LINQ聚合操作 Max()、Min()、Average()、Sum()方法 它们都位于Enumberable类中
            QueryStringWithOperators(); //用查询操作符建立查询表达式
            QueryStringWithEnumberableAndLambdas(); //通过Enumberable类型赋予Array的扩展方向建立查询表达式
            #endregion

            Console.ReadLine();
        }

        #region Lambda表达式——使用lambda表达式比匿名方法更节省代码和容易理解,其实lambda表达式是使用匿名函数Rredicate<T>的标准的匿名方法而已


        /// <summary>
        /// 使用传统的委托来调用FinAll()
        /// </summary>

        static void TraditionDelegateSyntax()
        {
            //创建一个整数列表
            List<int> list = new List<int>();
            list.AddRange(new int[] { 20, 1, 4, 8, 9, 44 });

            //使用传统委托语法调用FinAll()
            Predicate<int> callback = new Predicate<int>(IsEvenNumber);
            List<int> evenNumbers = list.FindAll(callback);
            foreach (int evenNumber in evenNumbers)
            {
                Console.WriteLine("{0}\t", evenNumber);
            }
        }
        static bool IsEvenNumber(int i)
        {
            return (i % 2) == 0;
        }

        /// <summary>
        /// 使用匿名方法,来调用FinAll()
        /// </summary>
        static void AnonymousMethodSyntax()
        {
            List<int> list = new List<int>();
            list.AddRange(new int[] { 20, 1, 4, 8, 9, 44 });
            //使用匿名方法
            List<int> evenNumbers = list.FindAll(delegate(int i)
            {
                return (i % 2) == 0;
            });

            foreach (int evenNumber in evenNumbers)
            {
                Console.WriteLine("{0}\t", evenNumber);
            }
        }

        /// <summary>
        /// 使用lambda表达式&&语句块Lambda表达式 代码更加简短
        /// </summary>
        static void LambdaExpressionSyntax()
        {
            List<int> list = new List<int>();
            list.AddRange(new int[] { 20, 1, 4, 8, 9, 44 });
            //现在使用lambda表达式,来调用FinAll()

            //List<int> evenNumbers = list.FindAll(x => (x % 2) == 0);

            //也可以使用语句块编写lambda表达式
            List<int> evenNumbers = list.FindAll(x =>
            {
                bool isEven = (x % 2) == 0;
                return isEven;
            });

            foreach (int evenNumber in evenNumbers)
            {
                Console.WriteLine("{0}\t", evenNumber);
            }
        }


        /// <summary>
        /// 访问包含的子对象
        /// </summary>
        /// <param name="myCars"></param>
        public static void GetFastCars(List<Car> myCars)
        {
            var fastCars = from c in myCars where c.Speed > 55 select c;
            foreach (var item in fastCars)
            {
                Console.WriteLine("{0} is going too fast!", item.PetName);
            }
        }

        /// <summary>
        /// 将LINQ查询应用与非泛型集合
        /// </summary>
        static void LINQOverArrayList()
        {
            //这是一个非泛型的集合
            ArrayList arrList = new ArrayList()
           {
                  new Car{PetName="Henry",Color="Silver",Speed=100,Make="BMW"},
                  new Car{PetName="Daisy",Color="Tan",Speed=90,Make="BMW"},
                  new Car{PetName="Mary",Color="Black",Speed=55,Make="VW"},
                  new Car{PetName="Clunker",Color="Rust",Speed=5,Make="Yugo"},
                  new Car{PetName="Melvin",Color="White",Speed=43,Make="Ford"}
           };

            //把ArrayList转换成一个贱人与IEnumberable<T>的类型
            var myCarsEnum = arrList.OfType<Car>();
            var fastCars = from c in myCarsEnum where c.Speed > 55 select c;

            foreach (var item in fastCars)
            {
                Console.WriteLine("{0} is going too fast!", item.PetName);
            }
        }

        /// <summary>
        /// 使用ofType<T>()筛选数据
        /// </summary>
        static void OfTypeAsFilter()
        {
            ArrayList myStuff = new ArrayList();
            myStuff.AddRange(new object[] { 10, 400, 8, false, new Car(), "string data" });
            var myInts = myStuff.OfType<int>();
            foreach (int i in myInts)
            {
                Console.WriteLine("Int value:{0}", i);
            }
        }

        /// <summary>
        /// 获取所有的数据
        /// </summary>
        /// <param name="products"></param>
        static void SelectEverything(ProductInfo[] products)
        {
            var allProducts = from p in products select p;
            foreach (var item in allProducts)
            {
                Console.WriteLine(item.ToString());
            }
        }

        /// <summary>
        /// 只提取产品的名字
        /// </summary>
        /// <param name="products"></param>
        static void ListProductNames(ProductInfo[] products)
        {
            var allProducts = from p in products select p.Name;
            foreach (var item in allProducts)
            {
                Console.WriteLine("Name:{0}", item);
            }
        }

        /// <summary>
        /// 获取数据子集
        /// </summary>
        /// <param name="products"></param>
        static void GetOverstock(ProductInfo[] products)
        {
            var overstock = from p in products where p.NumberInStock > 25 select p;
            foreach (var item in overstock)
            {
                Console.WriteLine(item.ToString());
            }
        }

        /// <summary>
        /// 投影新数据类型,可投影需要的数据
        /// </summary>
        /// <param name="products"></param>
        static void GetNamesAndDescriptions(ProductInfo[] products)
        {
            var nameDesc = from p in products select new { p.Name, p.Description };
            foreach (var item in nameDesc)
            {
                Console.WriteLine(item.ToString());
            }
        }

        /// <summary>
        /// 使用Enumberable获取总条数
        /// </summary>
        static void GetCountFromQuery()
        {
            string[] currentVideoGames = { "Morrowind", "Uncharted 2", "Fallout 3", "Daxter", "System Shock 2" };
            int num = (from c in currentVideoGames where c.Length > 6 select c).Count();

            Console.WriteLine("使用Enumberable获取的条数是{0}", num);
        }

        /// <summary>
        /// 反转结果集
        /// </summary>
        /// <param name="products"></param>
        static void ReversetEverything(ProductInfo[] products)
        {
            var allProducts = from p in products select p;
            foreach (var item in allProducts.Reverse())
            {
                Console.WriteLine(item.ToString());
            }
        }

        /// <summary>
        /// 对表达式中的数量进行升序排序
        /// </summary>
        /// <param name="products"></param>
        static void AlphabetizeProductNumber(ProductInfo[] products)
        {
            var subset = from p in products orderby p.NumberInStock select p;
            foreach (var item in subset)
            {
                Console.WriteLine(item.ToString());
            }
        }

        /// <summary>
        /// Except方法是返回包含两个容器不同之处的LINQ结果集,是返回第一个List中,在第二个List中没有出现过的值
        /// </summary>
        static void DisplayDiff()
        {
            List<string> myCars = new List<string> { "Yugo", "Aztec", "BMW" };
            List<string> yourCars = new List<string> { "BMW", "Saab", "Aztec" };
            var carDiff = (from c in myCars select c).Except(from c2 in yourCars select c2);
            foreach (var item in carDiff)
            {
                Console.WriteLine(item);
            }
        }

        /// <summary>
        /// Intersect方法是返回两个容器中共同的数据
        /// </summary>
        static void DiaplayIntersection()
        {
            List<string> myCars = new List<string> { "Yugo", "Aztec", "BMW" };
            List<string> yourCars = new List<string> { "BMW", "Saab", "Aztec" };
            //获取共同的成员
            var carIntersect = (from c in myCars select c).Intersect(from c2 in yourCars select c2);
            foreach (var item in carIntersect)
            {
                Console.WriteLine(item);
            }
        }

        /// <summary>
        /// Union方法返回是多个LINQ查询中的所有成员,如果相同成员出现过多次,将只能返回一个
        /// </summary>
        static void DisplayUnion()
        {
            List<string> myCars = new List<string> { "Yugo", "Aztec", "BMW" };
            List<string> yourCars = new List<string> { "BMW", "Saab", "Aztec" };
            //合并这两个容器
            var carUnion = (from c in myCars select c).Union(from c2 in yourCars select c2);
            foreach (var item in carUnion)
            {
                Console.WriteLine(item);
            }
        }

        /// <summary>
        /// 使用Concat()+foreach中调用distinct()方法,可移除重复的数据
        /// </summary>
        static void DisplayConcatNoDups()
        {
            List<string> myCars = new List<string> { "Yugo", "Aztec", "BMW" };
            List<string> yourCars = new List<string> { "BMW", "Saab", "Aztec" };
            var carConcat = (from c in myCars select c).Concat(from c2 in yourCars select c2);
            Console.WriteLine("移除重复数据");
            //使用Distinct可以返回非重复的值
            foreach (string item in carConcat.Distinct())
            {
                Console.WriteLine(item);
            }
        }

        /// <summary>
        /// LINQ聚合操作 Max()、Min()、Average()、Sum()方法 它们都位于Enumberable类中
        /// </summary>
        static void AggregateOps()
        {
            double[] winterTemps = { 2.0, -21.3, 8, -4, 0, 8.2 };
            //不同的聚合操作
            Console.WriteLine("Max temp:{0}",(from w in winterTemps select w).Max());
            Console.WriteLine("Min temp:{0}", (from w in winterTemps select w).Min());
            Console.WriteLine("Average temp:{0}", (from w in winterTemps select w).Average());
            Console.WriteLine("Sum temp:{0}", (from w in winterTemps select w).Sum());
        }

        /// <summary>
        /// 用查询操作符建立查询表达式
        /// </summary>
        static void QueryStringWithOperators() 
        {
            string[] currentVideoGames = { "Morrowind", "Uncharted 2", "Fallout 3", "Daxter", "System Shock 2" };
            var subset = from game in currentVideoGames where game.Contains(" ") orderby game select game;
            foreach (var item in subset)
            {
                Console.WriteLine(item);
            }
        }

        /// <summary>
        /// 通过Enumberable类型赋予Array的扩展方向建立查询表达式
        /// </summary>
        static void QueryStringWithEnumberableAndLambdas() 
        {
            Console.WriteLine("通过Enumberable类型赋予Array的扩展方向建立查询表达式");
            string[] currentVideoGames = { "Morrowind", "Uncharted 2", "Fallout 3", "Daxter", "System Shock 2" };
            //通过Enumberable类型赋予Array的扩展方向建立查询表达式
            var subset = currentVideoGames.Where(game => game.Contains(" ")).OrderBy(game => game).Select(game => game);
            foreach (var item in subset)
            {
                Console.WriteLine(item);
            }
        }


        #endregion

    }


    class Car
    {
        public string PetName { get; set; }
        public string Color { get; set; }
        public int Speed { get; set; }
        public string Make { get; set; }
    }

    class ProductInfo
    {
        public string Name { get; set; }
        public string Description { get; set; }
        public int NumberInStock { get; set; }

        public override string ToString()
        {
            return string.Format("Name={0},Description={1},Number in Stock={2}", Name, Description, NumberInStock);
        }
    }
}

Lambda表达式

标签:car   cat   derby   game   love   water   reac   san   getc   

原文地址:https://www.cnblogs.com/chaonuanxi/p/12174065.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!