Lambda下的常用操作=>(1)
【摘要】 使用Linq or Lambda进行查询,能感觉思路很清晰,昨天花了一个下午,今天花了一个下午,自己动手做了一些练习,总算是摸清了一些常用的操作。下面是我一些练习的代码。
int[] intarr = { 6, 1, 2, 3, 4, 5, 7, 8 }; string[] strarr = { "7", "10", "11", "8", "9" }; List...
使用Linq or Lambda进行查询,能感觉思路很清晰,昨天花了一个下午,今天花了一个下午,自己动手做了一些练习,总算是摸清了一些常用的操作。下面是我一些练习的代码。
int[] intarr = { 6, 1, 2, 3, 4, 5, 7, 8 }; string[] strarr = { "7", "10", "11", "8", "9" }; List<Person> list = new List<Person> { new Person(18,"well","a",800), new Person(19,"mike","b",600), new Person(25,"bruce","a",700), new Person(28,"summer","b",500), new Person(33,"energy","a",900), new Person(50,"water","c",1000), new Person(60,"spring","d",1200), new Person(61,"fisher","a",1100), new Person(65,"fish","a",400) }; Console.WriteLine("====int类型排序===="); var tx1 = intarr.OrderBy(x => x); foreach (var item in tx1) { Console.WriteLine(item); } Console.WriteLine("====string类型排序===="); var tx2 = strarr.OrderBy(x => Convert.ToInt32(x)); foreach (var item in tx2) { Console.WriteLine(item); } Console.WriteLine("====按年龄的降序排列===="); var tx3 = list.OrderByDescending(x => x.Age); foreach (var item in tx3) { Console.WriteLine("年龄:{0} 名字:{1}", item.Age.ToString(), item.Name); } Console.WriteLine("======类型转换 string转int====="); var tx4 = strarr.ToList<string>().ConvertAll<int>(x => Convert.ToInt32(x)); foreach (var item in tx4) { Console.WriteLine(item.GetType().ToString()); } Console.WriteLine("=====类型转换 int转string======"); var tx5 = intarr.ToList().ConvertAll<string>(x => x.ToString()); foreach (var item in tx5) { Console.WriteLine(item.GetType().ToString()); } Console.WriteLine("====数据集合并(1)去除重复项===="); var tx6 = intarr.Union(strarr.ToList().ConvertAll<int>(x => Convert.ToInt32(x))).OrderBy(x => x); ; foreach (var item in tx6) { Console.WriteLine(item); } Console.WriteLine("====数据集合并(2)取并集===="); var tx7 = intarr.Concat(strarr.ToList().ConvertAll<int>(x => Convert.ToInt32(x))).OrderBy(x => x); foreach (var item in tx7) { Console.WriteLine(item); } Console.WriteLine("====常用的聚合函数(1)求总数===="); var tx8 = intarr.Sum(); Console.WriteLine("总数为:"+tx8.ToString()); Console.WriteLine("====常用的聚合函数(2)求平均数===="); Console.WriteLine("平均数为:"+intarr.Average().ToString()); Console.WriteLine("====求最大数,最小数===="); Console.WriteLine("最大数:{0} 最小数:{1}",intarr.Max().ToString(),intarr.Min().ToString()); Console.WriteLine("====以国家进行分组 求人数========"); var tx9 = list.GroupBy(x => x.Country); foreach (var item in tx9) { Console.WriteLine("国家名:{0},人数:{1}",item.Key,item.Count().ToString()); } Console.WriteLine("====以国家分组 求平均工资======="); var tx10 = list.GroupBy(x => x.Country); foreach (var item in tx10) { Console.WriteLine("国家名:{0},平均工资:{1}",item.Key,item.Average(x=>x.Pay).ToString()); } Console.Read();
文章来源: brucedone.com,作者:大鱼的鱼塘,版权归原作者所有,如需转载,请联系作者。
原文链接:brucedone.com/archives/283
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)