1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.Xml.Linq; 7 using System.Collections; 8 9 10 namespace LinqDemos 11 { 12 class Program 13 { 14 static void Main(string[] args) 15 { 16 int[] num = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 1000 }; 17 var n = from number in num where number % 2 == 0 select number; 18 foreach (int a in n) 19 { 20 Console.WriteLine(a.ToString()); 21 } 22 ArrayList arr = new ArrayList(); 23 arr.Add(new Student { Name = "张三", Age = 12, Addresss = "莆田" }); 24 arr.Add(new Student { Name = "王三", Age = 12, Addresss = "福州" }); 25 var data = from Student stu in arr where stu.Name == "王三" select stu; 26 foreach (Student item in data) 27 { 28 Console.WriteLine(item.Name); 29 } 30 } 31 } 32 public class Student 33 { 34 public string Name { get; set; } 35 public int Age { get; set; } 36 public string Addresss { get; set; } 37 38 } 39 40 }
Linq是一种面向对象的查询方式,它和SQL语句及其类似,sql写法 select * from 表 Linq写法 from n in 数据源 select n;
为什么不跟sql写法一样将select一同写在语句的开头呢?主要是当时做IDE时考虑到智能感应,将select写在语句头不利于编程环境的智能感应,其中的奥妙自行百度理解哈,这边不详讲
Linq的查询对象可以是所有实现了IEnumerable的类型,比如数组,数据库集合(DataTable,DataSet...),Arraylist,List,
用Linq这种写法对于我们来说更加的直观,当然你也可以使用foreach和for。相对于这两种查询语句,Linq执行的效率和性能要优胜,
Linq>foreach>for