精通C# 第六版 -12 (LINQ to Object)
LINQ小实用的Demo,在学无止境的路上,每天一点小进步,知识才会累积成多嘛。
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Console.WriteLine("Fun LQIN to Object"); QueryOverStrings(); QueryOverInts(); IEnumerable<string> subset = GetSttringSubset(); foreach (var item in subset) { Console.WriteLine(item); } foreach (var item in GetStringSubsetArray()) { Console.WriteLine(item); } Console.WriteLine("***********LINQ over Generic collections***************"); List<Car> myCars = new List<Car>() { new Car{ PetName="Henry",Color="Silver",Speed=100,Mack="BMW"}, new Car{ PetName="Daisy",Color="Tan",Speed=90,Mack="BMW"}, new Car{ PetName="Mary",Color="Black",Speed=55,Mack="VW"}, new Car{ PetName="Clunker",Color="Rust",Speed=5,Mack="Yugo"}, new Car{ PetName="Melvin",Color="White",Speed=43,Mack="Ford"}, }; GetFastCars(myCars); GetFastBMWs(myCars); LINQOverArrayList(); OfTypeAsFilter(); ProductInfo[] itemInSrock = new[] { new ProductInfo{Name="Mac' s Coffee",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 Pops",Description="Cheezy,peppery goodness",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(itemInSrock); ListProductNames(itemInSrock); GetOverstock(itemInSrock); GetNameasDescriptions(itemInSrock); Array obj = GetProjectedSubset(itemInSrock); foreach (var item in obj) { Console.WriteLine(item.ToString()); } GetCountFromQuery(); ReverseFromQuery(itemInSrock); DispalyConcatNoDups(); AvggregateOps(); QueryStringWithEnumberableAndLambdas(); Console.ReadLine(); } #region LINQ /// <summary> /// 将LINQ查询应用于原始数组 /// </summary> static void QueryOverStrings() { string[] currentVideoGames = { "Morrowind", "Uncharted 2", "Fallout 3", "Daxter", "System Shock 2" }; IEnumerable<string> subset = from g in currentVideoGames where g.Contains(" ") orderby g select g; foreach (var item in subset) { Console.WriteLine("Item:{0}", item); } } /// <summary> /// LINQ和隐式类型本地变量 /// </summary> static void QueryOverInts() { int[] number = { 10, 20, 30, 40, 1, 2, 3, 9 }; IEnumerable<int> subset = from i in number where i < 10 select i; foreach (var item in subset) { Console.WriteLine("Item:{0}", item); } } /// <summary> /// 立即执行的作用,并返回Int的数组和集合 /// </summary> static void ImmediateExecution() { int[] number = { 10, 20, 30, 40, 1, 2, 3, 9 }; //立即获取数据为int[] int[] subsetIntArray = (from i in number where i < 10 select i).ToArray<int>(); //立即获取数据为List<Int> List<int> subsetAsListArray = (from i in number where i < 10 select i).ToList<int>(); } /// <summary> /// 使用IEnumberable,返回LINQ查询的结果 /// </summary> /// <returns></returns> static IEnumerable<string> GetSttringSubset() { string[] colors = { "Light Red", "Green", "Yellow", "Dark Red", "Red", "Purple" }; //注意,subset是Ienumberable<string>兼容的对象 IEnumerable<string> theRedColor = from c in colors where c.Contains("Red") select c; return theRedColor; } /// <summary> /// 通过立即执行返回LINQ结果,返回toArray 数组类型 /// </summary> /// <returns></returns> static string[] GetStringSubsetArray() { string[] colors = { "Light Red", "Green", "Yellow", "Dark Red", "Red", "Purple" }; var theRedColor = from i in colors where i.Contains("Red") select i; //将结果映射为数组 return theRedColor.ToArray(); } /// <summary> /// 访问包含的子对象,抓取Speed属性大于55的项 /// </summary> /// <param name="myCars"></param> 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> /// 抓取Speed属性大于90的宝马车 /// </summary> /// <param name="myCars"></param> static void GetFastBMWs(List<Car> myCars) { var fastCars = from c in myCars where c.Speed > 90 && c.Mack == "BMW" select c; foreach (var item in fastCars) { Console.WriteLine("{0} is going too fast!", item.PetName); } } /// <summary> /// 将LINQ查询应用于非泛型集合 /// </summary> static void LINQOverArrayList() { Console.WriteLine("***********LINQ over ArrayList************"); ArrayList myCars = new ArrayList() { new Car{ PetName="Henry",Color="Silver",Speed=100,Mack="BMW"}, new Car{ PetName="Daisy",Color="Tan",Speed=90,Mack="BMW"}, new Car{ PetName="Mary",Color="Black",Speed=55,Mack="VW"}, new Car{ PetName="Clunker",Color="Rust",Speed=5,Mack="Yugo"}, new Car{ PetName="Melvin",Color="White",Speed=43,Mack="Ford"}, }; //把arrayList转换为一个兼容于IENumberable<T>类型 var myCarsEnum = myCars.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>筛选数据,<T> 是返回数据的类型 OfType<Int>即集合中的Int数据,则只返回Int数据 /// </summary> static void OfTypeAsFilter() { ArrayList arr = new ArrayList(); arr.AddRange(new object[] { 10, 400, 8, false, new Car(), "String data" }); var myInts = arr.OfType<int>(); foreach (var item in myInts) { Console.WriteLine("Int Value:{0}", item); } } /// <summary> /// 基本的选择语法 /// </summary> /// <param name="products"></param> static void SelectEverything(ProductInfo[] products) { //得到所有的对象 Console.WriteLine("All Product details"); var allProducts = from p in products select p; foreach (var item in allProducts) { Console.WriteLine("Name:{0}", item); } } /// <summary> /// 使用LINQ语法只提取产品的名字 /// </summary> /// <param name="products"></param> static void ListProductNames(ProductInfo[] products) { //只获取产品的名字 Console.WriteLine("Only Product Name:"); var allProducts = from p in products select p.Name; foreach (var item in allProducts) { Console.WriteLine("Name:{0}", item); } } /// <summary> /// 使用LINQ提取库存量大于25的项 /// </summary> /// <param name="products"></param> static void GetOverstock(ProductInfo[] products) { //只获取产品的名字 Console.WriteLine("the overstock item:"); var overstock = from p in products where p.NumberInStock > 25 select p; foreach (var item in overstock) { Console.WriteLine(item.ToString()); } } /// <summary> /// 投影新数据类型,select new {返回只需要的值} /// </summary> /// <param name="products"></param> static void GetNameasDescriptions(ProductInfo[] products) { Console.WriteLine("Name And Descriotions:"); var nameDesc = from p in products select new { p.Name, p.Description }; foreach (var item in nameDesc) { Console.WriteLine(item.ToString()); } } /// <summary> /// 使用ToArray()扩展方法,将查询结果转换为.NET System.Array对象 也返回select new {p.Name,p.Description} /// </summary> /// <param name="products"></param> /// <returns></returns> static Array GetProjectedSubset(ProductInfo[] products) { var nameDesc = from p in products select new { p.Name, p.Description }; return nameDesc.ToArray(); } /// <summary> /// 使用IEnumberable获取总数 /// </summary> static void GetCountFromQuery() { string[] currentVideoGames = { "Morrowind", "Uncharted 2", "Fallout 3", "Daxter", "System Shock 2" }; int num = (from i in currentVideoGames where i.Length > 6 select i).Count(); Console.WriteLine("{0}Items honor the LINQ query.", num); } /// <summary> /// 反转结果集 /// </summary> /// <param name="products"></param> static void ReverseFromQuery(ProductInfo[] products) { Console.WriteLine("Product in reverse"); var allProducts = from p in products select p; foreach (var item in allProducts.Reverse()) { Console.WriteLine(item.ToString()); } } /// <summary> /// 对表达式进行排序,默认为正序,你也可以使用ascending操作符,逆序可以使用descending操作符 /// </summary> /// <param name="products"></param> static void AlPhabetizeProductNames(ProductInfo[] products) { //按字母排序获取产品的名称 var allProducts = from p in products orderby p.Name select p; Console.WriteLine("orderby name"); foreach (var item in allProducts.Reverse()) { Console.WriteLine(item.ToString()); } } /// <summary> /// 移除重复值 /// </summary> static void DispalyConcatNoDups() { 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 c1 in yourCars select c1); foreach (var item in carConcat.Distinct()) Console.WriteLine(item); } /// <summary> /// 不同的聚合函数(max、min、avg、sum) /// </summary> static void AvggregateOps() { double[] temps = { 2.0, -21.3, 8, -4, 0, 8.2 }; //不同的聚合函数 Console.WriteLine("MAX:{0}",(from c in temps select c).Max()); Console.WriteLine("Min:{0}", (from c in temps select c).Min()); Console.WriteLine("Average:{0}", (from c in temps select c).Average()); Console.WriteLine("Sum:{0}", (from c in temps select c).Sum()); } /// <summary> /// 通过Enumbetable类型赋array的扩展方法建立查询表达式 /// </summary> static void QueryStringWithEnumberableAndLambdas() { string[] currentVideoGames = { "Morrowind", "Uncharted 2", "Fallout 3", "Daxter", "System Shock 2" }; //通过Enumbetable类型赋array的扩展方法建立查询表达式 var subset = currentVideoGames.Where(x => x.Contains(" ")).OrderBy(x => x).Select(x => x); foreach (var item in subset) Console.WriteLine("item:{0}",item); } #endregion } class Car { public string PetName { get; set; } public string Color { get; set; } public int Speed { get; set; } public string Mack { 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},NumberInStock={2}", Name, Description, NumberInStock); } } }
生命中最值得欣慰的,莫过于一觉醒来,你还在身旁