DAY 22
1

## DAY 22 LINQ 查詢運算式

### LINQ

Language Integrated Query (LINQ) 是一組以直接將查詢功能整合至 C# 語言為基礎之技術的名稱。
「查詢」是指從資料來源中擷取資料的運算式。查詢通常以特定的查詢語言來表示。

``````int[] scores = new int[] { 97, 92, 81, 60 };

// Define the query expression.
IEnumerable<int> scoreQuery =
from score in scores
where score > 80
select score;
``````

``````int[] scores = new int[] { 97, 92, 81, 60 };

// Define the query expression.
var scoreQuery = scores
.Where (x => x > 80)
.Select (x => x);
``````

scores 為欲查詢集合，Where 引數為 Predicate 提供給他一個篩選條件，Select 引數為 Func 告訴他我們需要傳回什麼內容，忘了 Predicate 與 Func 可以看 DAY 17 委派的介紹。

### Select

Select 可以將集合內的元素轉換成新的樣式，如

``````int[] scores = new int[] { 97, 92, 81, 60 };

var scoresAdd2 = scores
.Select (x => x + 2);

var scoresToString = scores
.Select (x => x + "");
``````

``````var members = new List<Member> () {
new Member () { ID = 0, Name = "Mio" },
new Member () { ID = 1, Name = "Miffy" },
new Member () { ID = 2, Name = "Lulu" },
new Member () { ID = 3, Name = "NekoSan" }
};

var names = members
.Select (x => x.Name);
var membersAddProperty = members
.Select (x =>
new {
ID = x.ID,
Name = x.Name,
IDName = \$"ID = {x.ID}, Name = {x.Name}"
});
``````

### Where

Where 可以將集合內符合條件的元素取出，如

``````var members = new List<Member> () {
new Member () { ID = 0, Name = "Mio" },
new Member () { ID = 1, Name = "Miffy" },
new Member () { ID = 2, Name = "Lulu" },
new Member () { ID = 3, Name = "NekoSan" }
};

var membersNameContainsMi = members
.Where (x => x.Name.Contains ("Mi"));
``````

``````int[] scores = new int[] { 97, 92, 81, 60 };

var scoresAddNo = scores
.Select ((x, y) => new { score = x, No = y });

var scoresWhereNo2 = scores
.Where ((x, y) => y == 2);
``````

### Count

Count 可以獲得集合內的元素數量，如

``````var members = new List<Member> () {
new Member () { ID = 0, Name = "Mio" },
new Member () { ID = 1, Name = "Miffy" },
new Member () { ID = 2, Name = "Lulu" },
new Member () { ID = 3, Name = "NekoSan" }
};

var membersCount = members
.Count ();
``````

``````var membersNameContainsMiCount = members
.Count (x => x.Name.Contains ("Mi"));
``````

### OrderBy

OrderBy 可以將集合內的元素重新排序，如

``````int[] scores = new int[] { 97, 92, 81, 60 };

var scoresAddNoOrderByScore = scores
.Select ((x, y) => new { score = x, No = y })
.OrderBy (x => x.score);
``````