标签:where from oftype group orderby join
===========================================Racer.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections; namespace ConsoleApplication4 { [Serializable] public class Racer:IComparable<Racer>,IFormattable { public string FirstName { get; private set; }//第一个武将 public string LastName { get; private set; }//第二个武将 public int Wins { get; private set; }//赢得次数 public string Country { get; private set; }//国家 public int Starts { get; private set; }//开始 public string[] Arms { get; private set; }//武器 public int[] Years { get; private set; }//年份 public Racer(string firstname = "", string lasename = "", int wins = 0, string country = "", int starts = 0, IEnumerable<string> Arms = null, IEnumerable<int> years = null) { this.FirstName = firstname; this.LastName = lasename; this.Wins = wins; this.Country = country; this.Starts = starts; List<string> LArms = new List<string>(); foreach (var item in Arms) { LArms.Add(item); } this.Arms = LArms.ToArray(); List<int> Lyears = new List<int>(); foreach (var item in years) { Lyears.Add(item); } this.Years = Lyears.ToArray(); } public int CompareTo(Racer other) { if (other == null) throw new ArgumentNullException("对象不能为空"); return this.Wins.CompareTo(other.Wins); } public string ToString(string format, IFormatProvider formatProvider) { switch (format) { case "": return ToString(); case "C": StringBuilder sb = new StringBuilder(); foreach (var item in Arms) { sb.Append(item + ","); } return sb.ToString().TrimEnd(‘,‘); case "Y": StringBuilder sb2 = new StringBuilder(); foreach (var item in Years) { sb2.Append(item + ","); } return sb2.ToString().TrimEnd(‘,‘); default: return ToString(); } } public override string ToString() { return string.Format("第一个赛手:{0},最后一个赛手:{1},赢的次数:{2},国家:{3},开始:{4}",this.FirstName,this.LastName,this.Wins.ToString(),this.Country,this.Starts.ToString()); } } }
===========================================Team.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication4 { [Serializable] public class Team { public string Name { get; private set; }//团队名称 public int[] Years { get; private set; } public Team(string name,params int[] years) { this.Name = name; this.Years = years; } } }
===========================================Formula.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication4 { public static class Formula { private static List<Racer> racers; private static List<Team> team; public static IList<Racer> GetChampions() { if (racers == null) { racers = new List<Racer>(); racers.Add(new Racer("张飞", "关羽", 100, "蜀国", 10, new string[] { "丈八蛇矛", "青龙偃月刀" }, new int[] { 200, 201, 202 })); racers.Add(new Racer("张飞", "关羽", 99, "蜀国", 10, new string[] { "丈八蛇矛", "青龙偃月刀" }, new int[] { 200, 201, 202 })); racers.Add(new Racer("黄忠", "魏延", 80, "蜀国", 10, new string[] { "穿杨弓", "大***" }, new int[] {203})); racers.Add(new Racer("许褚", "典韦", 95, "魏国", 10, new string[] { "大铁锤", "双戟" }, new int[] { 195, 212 })); racers.Add(new Racer("张辽", "徐晃", 90, "魏国", 10, new string[] { "长把子刀", "长把子斧" }, new int[] { 205, 106, 215 })); racers.Add(new Racer("程普", "黄盖", 96, "吴国", 10, new string[] { "龙虎鞭", "大刀" }, new int[] { 190, 191, 202,207 })); racers.Add(new Racer("周泰", "太史慈", 88, "吴国", 10, new string[] { "无敌身躯", "火箭枪" }, new int[] { 195, 196, 197 })); } return racers; } public static IList<Team> GetConstructorChampions() { if (team == null) { team = new List<Team>(); team.Add(new Team("兄弟队", new int[] { 200, 201, 202 })); team.Add(new Team("死党队", new int[] { 203 })); team.Add(new Team("虎营队", new int[] { 195, 212 })); team.Add(new Team("良将队", new int[] { 205, 106, 215 })); team.Add(new Team("老将队", new int[] { 190, 191, 202, 207 })); team.Add(new Team("不死队", new int[] { 195, 196, 197 })); } return team; } } }
===========================================Racer_IEqualityComparer.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication4 { public class Racer_IEqualityComparer:IEqualityComparer<Racer> { //只比较Racer对象的FirstName属性 public bool Equals(Racer x, Racer y) { return x.FirstName==y.FirstName; } public int GetHashCode(Racer obj) { return obj.FirstName.GetHashCode(); } } }
===========================================主程序
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections; using System.Collections.Concurrent; namespace ConsoleApplication4 { class Program { static void Main(string[] args) { //筛选(查询赢了至少95场的吴国和蜀国军队军队)*************************************************************** //--Linq var query1 = from r in Formula.GetChampions() where r.Wins >= 95 && (r.Country == "吴国" || r.Country == "蜀国") select r; //--扩展方法 IEnumerable<Racer> ir1 = Formula.GetChampions(). Where(r => r.Wins >= 95 && (r.Country == "吴国" || r.Country == "蜀国")).Select(r => r); Foreach(query1); Foreach(ir1); //索引筛选(查询赢了大于85场的、索引为偶数的军团)************************************************************ //--扩展方法 IEnumerable<Racer> ir2 = Formula.GetChampions().Where((r, index) => r.Wins > 85 && index % 2 == 0).Select(r => r); Foreach(Formula.GetChampions()); Foreach(ir2); //类型筛选************************************************************************************************** //--扩展方法 object[] o = new object[] { 1, 2, "张飞", 2, "关二爷", true, 1.1 }; IEnumerable<string> is1 = o.OfType<string>();//筛选为string类型的元素 Foreach(is1); //复合from子句(查询所有的武器)******************************************************************************* //--Linq var query2 = from r in Formula.GetChampions() from c in r.Arms select c; Foreach(query2); //--扩展方法 IEnumerable<string> is2 = Formula.GetChampions().SelectMany(r => r.Arms, (r, a) => new { Racer = r, Amrs = a }). Select(r => r.Racer.FirstName + "|" + r.Racer.LastName + "=>" + r.Amrs); Foreach(is2); //排序(先按照第一个姓名降序排序,在按照赢得次数升序排序,返回10个数据)**************************************** //--Linq var query3 = (from r in Formula.GetChampions() orderby r.FirstName descending, r.Wins ascending select r).Take(10); Foreach(query3); //--扩展方法 IEnumerable<Racer> is3 = Formula.GetChampions().OrderByDescending(r => r.FirstName).ThenBy(r => r.Wins).Select(r => r);//第一种方法(ThenBy) IEnumerable<Racer> is4 = Formula.GetChampions().OrderByDescending(r => r.FirstName). CreateOrderedEnumerable(r => r.Wins, Comparer<int>.Default, true).Select(r => r).Take(10);//第二种方法(CreateOrderedEnumerable) Foreach(is4); //分组(根据国家分组,并且只显示军团大于或等于2的国家)************************************************************ //--Linq var query4 = from r in Formula.GetChampions() group r by r.Country into g where g.Count() >= 2 select new { Count = g.Count(), Key = g.Key }; foreach (var item in query4) { Console.WriteLine("国家:{0}。军团数:{1}", item.Key, item.Count); } //--扩展方法 var is5 = Formula.GetChampions().GroupBy(r => r.Country).Where(r => r.Count() >= 2).Select(r => new { Count = r.Count(), Key = r.Key }); foreach (var item in is5) { Console.WriteLine("国家:{0}。军团数:{1}", item.Key, item.Count); } Console.WriteLine("================================================"); //对嵌套的对象分组(对国家进行分组,查询出国家名称,国家的军团数,军队的将军)****************************** //--Linq var query5 = from r in Formula.GetChampions() group r by r.Country into g select new { Key = g.Key, Count = g.Count(), Name = from n in g select new { LastName = n.LastName, FirstName = n.FirstName } }; foreach (var item in query5) { Console.WriteLine("国家:{0}。军团数:{1}", item.Key, item.Count); foreach (var subitem in item.Name) { Console.WriteLine("军队的将军:" + subitem.FirstName + "|" + subitem.LastName); } } Console.WriteLine("================================================"); //--扩展方法 var is6 = Formula.GetChampions().GroupBy(r => r.Country). Select(r => new { Country = r.Key, Count = r.Count(), Name = r.Select(n => new { FristName = n.FirstName, LastName = n.LastName }) }); foreach (var item in query5) { Console.WriteLine("国家:{0}。军团数:{1}", item.Key, item.Count); foreach (var subitem in item.Name) { Console.WriteLine("军队的将军:" + subitem.FirstName + "|" + subitem.LastName); } } Console.WriteLine("================================================"); //连接(查询年份大于195的军团和将军)****************************************************************************** //--Linq 【语法: from r in 第一个对象 join t in 第二个对象 on r.one equals t.one select new { }】 int myyear = 190; var query7 = from racer in from r in Formula.GetChampions() from ry in r.Years where ry > myyear select new { Year = ry, Name = r.FirstName + "|" + r.LastName } join team in from t in Formula.GetConstructorChampions() from ty in t.Years where ty > myyear select new { Year = ty, Name = t.Name } on racer.Year equals team.Year select new { TeamName = team.Name, Year = team.Year, Name = racer.Name }; foreach (var item in query7) { Console.WriteLine("军团:{0},将军:{1},年份:{2}", item.TeamName, item.Name, item.Year); } Console.WriteLine("================================================"); //集合操作********************************************************************************************************************** //Racer_IEqualityComparer类实现了IEqualityComparer,只比较Racer对象的FirstName属性 //委托,传一个武器名称,查询属于该武器的所有元素 Func<string, IEnumerable<Racer>> myracer = racer => from r in Formula.GetChampions() from a in r.Arms where a == racer select r; //----Distinct() 排除重复的数据 Foreach(Formula.GetChampions().Distinct(new Racer_IEqualityComparer())); //----Union() 并集 【(1,2,3,5)并集(5,6)=(1,2,3,5,6)】 Foreach(myracer("长把子刀").Union(myracer("大***"))); //----Intersect 交集 【(1,2,3,5)交集(5,6)=(5)】 Foreach(Formula.GetChampions().Intersect(myracer("大***"))); //----Except 差集 【(1,2,3,5)差集(5,6)=(1,2,3)】 Foreach(Formula.GetChampions().Except(myracer("大***"))); //合并************************************************************************************************************************* Foreach(myracer("长把子刀").Zip(myracer("大***"), (r, t) => r.FirstName + "|" + t.FirstName));//输出:张辽|黄忠 //分区【Skip:跳过指定数量的元素】【Take:显示的数量】************************************************************************* int pageindex = 1;//当前页 int pagesize = 3;//每夜显示多少数据 Foreach(Formula.GetChampions().Skip(pageindex * pagesize).Take(pagesize)); //聚合操作符(返回一个值)****************************************************************************************************** //----Count() 返回集合中的项数 Foreach(from r in Formula.GetChampions() select r.Years.Count()); //----Sum() 返回所有数字的和 Console.WriteLine((from r in Formula.GetChampions() select r.Years.Count()).Sum()); //----Min() 返回集合中最小的元素 Console.WriteLine((from r in Formula.GetChampions() select r.Years.Count()).Min()); //----Max() 返回集合中最小的元素 Console.WriteLine((from r in Formula.GetChampions() select r.Years.Count()).Max()); //----Average() 返回集合的平均值 Console.WriteLine((from r in Formula.GetChampions() select r.Years.Count()).Average()); //----Aggregate() 聚合运算 Console.WriteLine((from r in Formula.GetChampions() select r.Years.Count()).Aggregate((a, b) => a * b)); //转换(根据将军查询武器)*********************************************************************************************** //查询可以推迟到访问数据项时再执行,在迭代中使用查询时,查询会执行。而使用转换操作符会立即执行查询,把查询放在数组,列表或字典中 var query8 = (from r in Formula.GetChampions() select new { Name = r.FirstName, Racer = r }).ToList().ToLookup(r => r.Name, r => r.Racer); Foreach(query8["张飞"]); //在非类型化的集合上(如ArrayList)使用Linq查询,就可以使用cast()方法 ArrayList abc= new ArrayList(); var aaaaa = (from ii in abc.Cast<Racer>() select ii); //操作符***************************************************************************************************************** //--填充一个范围的数字 Foreach(Enumerable.Range(1, 20).Where(r => r > 10).Select(r => r)); //--返回一个空集合 List<string> l = Enumerable.Empty<string>().ToList(); //生成一个重复值的序列 Foreach(Enumerable.Repeat("asd", 3)); Console.ReadKey(); } static void Foreach<T>(IEnumerable<T> s) { foreach (T item in s) { Console.WriteLine(item); } //Parallel.ForEach(s, i => Console.WriteLine(i)); Console.WriteLine("========================="); } } }
本文出自 “程序猿的家” 博客,请务必保留此出处http://962410314.blog.51cto.com/7563109/1554536
标签:where from oftype group orderby join
原文地址:http://962410314.blog.51cto.com/7563109/1554536