[C#.Net&Linq]LINQ to Object 學習筆記(基本語法)
※基本語法
※from…in…where…select –>句法解釋:from(取出元素)in(在某集合裡)where(對from取出的元素進行篩選)select(把結果取出)
1: static void Main(string[] args)
2: {
3: //建立資料來源
4: string[] weekDayList = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };
5: //語法組 以from開頭,用selec或group做為結束
6: //這邊用三種方法來簡單描述,如何對資料進行查詢
7: var Original_Query = from q in weekDayList
8: select q;
9: Console.WriteLine("列舉出陣列weekDayList元素:");
10: foreach (var item in Original_Query)
11: {
12: Console.WriteLine(item);
13: }
14:
15: //方式一 使用 from...in...where...select
16: IEnumerable<string> Query1 = from q in weekDayList //或 var Query1 = from q in weekDayList...使用匿名型別(var)(下方類推)
17: where q.StartsWith("S")
18: select q;
19: Console.WriteLine("列舉出方法一篩選weekDayList元素:");
20: foreach (var item in Query1)
21: {
22: Console.WriteLine(item);
23: }
24:
25: //方式二 使用泛型委派
26: Func<string, IEnumerable<string>> query = (initLetter) =>
27: {
28: return weekDayList.Where(q => q.StartsWith(initLetter));
29: };
30: IEnumerable<string> Query2 = query("M");
31: Console.WriteLine("列舉出方法二篩選weekDayList元素:");
32: foreach (var item in Query2)
33: {
34: Console.WriteLine(item);
35: }
36:
37: //方式三 直接使用集合物件的方法where
38: IEnumerable<string> Query3 = weekDayList.Where(q => q.StartsWith("T"));
39: Console.WriteLine("列舉出方法三篩選weekDayList元素:");
40: foreach (var item in Query3)
41: {
42: Console.WriteLine(item);
43: }
44: Console.ReadKey();
45: }
46: }