C#Linq的使用


 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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM