LinQ可以簡化原本要成程式碼做Db的語法與連接,用更直覺的方式寫資料的讀取,也能讓程式碼更容易讀懂用途。
// Query #1.
List<int> numbers = new List<int>() { 5, 4, 3, 2, 0 };
//查詢語法
From 變數 in Table
Where 條件
Select 欄位
IEnumerable<int> filteringQuery =
from num in numbers
where num < 3
select num;
回傳型別是 IEnumerable<T>
。 所有的查詢都可使用var來撰寫,並且可以用foreach的方式讀取資料
foreach(item in filteringQuery){
...
}
int numCount2 = numbersQuery.Count();
int numCount1 =
(from num in numbers
where num < 10
select num).Count();
查詢方式可以簡化成
int numCount1 = numbers.Where(w => w <10).Count();
var products =
from product in Model.Products
orderby product.Price
select product;
from object in objects
group object by condition into o
orderby o.Key
select o;
List<string> Names = new List<string>{"Mandy","Bob","Jobs"};
轉換成陣列
string[] NameArray = Names.ToArray();
轉換成List
List<string> NameList = NameArray.ToList();