C# Linq基本常用用法
1.什么是Linq?
Lanaguage Interated Query(语言集成查询),Linq 是集成C# 和VB这些语言中用于提供数据查询能力的一个新特性。
这里只介绍两种基本常用用法。
学习方法参考示例代码
1) where 查询
class Program { static void Main(string[] args) { int[] nums = new int[] { 10, 2, 3, 100, 1, 5, 17, 82, 22, 3 }; var result = from m in nums where m >= 10 select m; foreach (var v in result) { Console.WriteLine("v:" + v + " "); } Console.WriteLine("\n"); //使用Lambda 表达式进行Linq查询 var result2 = nums.Where(m => m >= 10); foreach (var v in result2) { Console.WriteLine("v2:" + v + " "); } List<People> mans = new List<People>(); mans.Add(new People { id = 10, sex = true, name = "小王", birthday = Convert.ToDateTime("1994-1-1") }); mans.Add(new People { id = 11, sex = false, name = "小张", birthday = Convert.ToDateTime("1954-1-1") }); mans.Add(new People { id = 12, sex = true, name = "小明", birthday = Convert.ToDateTime("1993-1-1") }); mans.Add(new People { id = 13, sex = false, name = "小红", birthday = Convert.ToDateTime("1974-1-1") }); var resultMan = from man in mans where man.id < 11 && man.sex select man; foreach (var v in resultMan) { Console.WriteLine("v:"+v.id + " name :"+v.name); } Console.Read(); } } class People { public string name { get; set; } public int id { get; set; } public bool sex { get; set; } public DateTime birthday { get; set; } public int GetAge() { return DateTime.Now.Year - birthday.Year; } }
2) order 排序
descending 降序
ascending 升序
1 List<int> numbers = new List<int>() { 10, 11, 1, 2, 3, 7, 6 }; 2 3 var resultNums = from m in numbers orderby m select m; 4 foreach (var v in resultNums) 5 { 6 Console.WriteLine("v num:"+v); 7 } 8 Console.WriteLine("\n"); 9 var resultNums2 = from m in numbers orderby m descending select m; 10 foreach (var v in resultNums2) 11 { 12 Console.WriteLine("v2 num:" + v); 13 } 14 Console.WriteLine("\n"); 15 16 var resultNums3 = from m in numbers orderby m ascending select m; 17 foreach (var v in resultNums3) 18 { 19 Console.WriteLine("v3 num:" + v); 20 }
2.优点
1.简单,容易上手,极大节省开发效率。
2.很大程度上节省代码量。
建议:Unity开发的话,一般都不要去使用,会产生GC。
参考链接:http://www.cnblogs.com/jara/p/3472215.html http://www.cnblogs.com/hgmyz/p/7068150.html
学以致用,不致用,何学?