DAY 19
0
Modern Web

## Day19_LINQ前序

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;
``````

``````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();
``````

#### 排序

• OrderBy(升冪排序)
• OrderByDescending(降冪排序)
• ThenBy(二次升冪排序)
• ThenByDescending(二次降冪排序)
• Reverse(反轉集合中的物件排列順序)
如:以價錢排序
``````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<string> NameList = NameArray.ToList();
``````