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(); IEnumerablesubset = GetSttringSubset(); foreach (var item in subset) { Console.WriteLine(item); } foreach (var item in GetStringSubsetArray()) { Console.WriteLine(item); } Console.WriteLine("***********LINQ over Generic collections***************"); List myCars = new List () { 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 /// /// 将LINQ查询应用于原始数组 /// static void QueryOverStrings() { string[] currentVideoGames = { "Morrowind", "Uncharted 2", "Fallout 3", "Daxter", "System Shock 2" }; IEnumerablesubset = from g in currentVideoGames where g.Contains(" ") orderby g select g; foreach (var item in subset) { Console.WriteLine("Item:{0}", item); } } /// /// LINQ和隐式类型本地变量 /// static void QueryOverInts() { int[] number = { 10, 20, 30, 40, 1, 2, 3, 9 }; IEnumerablesubset = from i in number where i < 10 select i; foreach (var item in subset) { Console.WriteLine("Item:{0}", item); } } /// /// 立即执行的作用,并返回Int的数组和集合 /// 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(); //立即获取数据为List List subsetAsListArray = (from i in number where i < 10 select i).ToList (); } /// /// 使用IEnumberable,返回LINQ查询的结果 /// ///static IEnumerable GetSttringSubset() { string[] colors = { "Light Red", "Green", "Yellow", "Dark Red", "Red", "Purple" }; //注意,subset是Ienumberable 兼容的对象 IEnumerable theRedColor = from c in colors where c.Contains("Red") select c; return theRedColor; } /// /// 通过立即执行返回LINQ结果,返回toArray 数组类型 /// ///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(); } /// /// 访问包含的子对象,抓取Speed属性大于55的项 /// /// static void GetFastCars(ListmyCars) { 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); } } /// /// 抓取Speed属性大于90的宝马车 /// /// static void GetFastBMWs(ListmyCars) { 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); } } /// /// 将LINQ查询应用于非泛型集合 /// 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类型 var myCarsEnum = myCars.OfType (); 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); } } /// /// 使用OfType static void OfTypeAsFilter() { ArrayList arr = new ArrayList(); arr.AddRange(new object[] { 10, 400, 8, false, new Car(), "String data" }); var myInts = arr.OfType筛选数据, 是返回数据的类型 OfType 即集合中的Int数据,则只返回Int数据 /// (); foreach (var item in myInts) { Console.WriteLine("Int Value:{0}", item); } } /// /// 基本的选择语法 /// /// 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); } } ////// 使用LINQ语法只提取产品的名字 /// /// 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); } } ////// 使用LINQ提取库存量大于25的项 /// /// 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()); } } ////// 投影新数据类型,select new {返回只需要的值} /// /// 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()); } } ////// 使用ToArray()扩展方法,将查询结果转换为.NET System.Array对象 也返回select new {p.Name,p.Description} /// /// ///static Array GetProjectedSubset(ProductInfo[] products) { var nameDesc = from p in products select new { p.Name, p.Description }; return nameDesc.ToArray(); } /// /// 使用IEnumberable获取总数 /// 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); } ////// 反转结果集 /// /// 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()); } } ////// 对表达式进行排序,默认为正序,你也可以使用ascending操作符,逆序可以使用descending操作符 /// /// 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()); } } ////// 移除重复值 /// static void DispalyConcatNoDups() { ListmyCars = new List () { "Yugo", "Aztec", "BMW" }; List yourCars = new List () { "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); } /// /// 不同的聚合函数(max、min、avg、sum) /// 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()); } ////// 通过Enumbetable类型赋array的扩展方法建立查询表达式 /// 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); } } }