本文將介紹如何利用 LINQ 語法和 Lambda 表示式來對陣列進行查詢。
當您嘗試在陣列中尋找符合某些條件的值,並希望知道它在陣列中的 Index 為何,可以不須使用跑迴圈的方式,利用 LINQ 語法搭配 Lambda 表示式,就可以輕鬆完成。
以下程式碼示範利用如何找出陣列中,值為 True 的值及其索引:
【VB.NET】
1: Module Module1
2:
3: Sub Main()
4: Dim a(9) As Boolean
5: a(2) = True : a(3) = True : a(6) = True : a(7) = True : a(9) = True
6:
7: For i As Integer = 0 To a.Length - 1
8: Console.WriteLine(String.Format("{0},{1}", i.ToString(), a(i).ToString()))
9: Next
10:
11: Console.WriteLine("--------------------------------------")
12:
13: Dim b = a.Select(Function(i, j) New With {Key .item = i, Key .idx = j})
14: b = From p In b Where p.item = True Select p
15:
16: For Each i In b
17: Console.WriteLine(String.Format("{0},{1}", i.idx, i.item))
18: Next
19:
20: Console.ReadKey()
21: End Sub
22:
23: End Module
【C#】
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Text;
5:
6: namespace ConsoleApplication2_NET35
7: {
8: class Program
9: {
10: static void Main(string[] args)
11: {
12: bool[] a = new bool[10];
13: a[2] = a[3] = a[6] = a[7] = a[9] = true;
14:
15: for (int i = 0; i < a.Length; i++)
16: {
17: Console.WriteLine(string.Format("{0},{1}", i.ToString(), a[i].ToString()));
18: }
19:
20: Console.WriteLine("--------------------------------------");
21: var b = a.Select((i, j) => new { item = i, idx = j });
22: b = from p in b
23: where p.item == true
24: select p;
25: foreach(var i in b)
26: {
27: Console.WriteLine(string.Format("{0},{1}", i.idx,i.item));
28: }
29:
30:
31: Console.ReadKey();
32: }
33: }
34: }
【執行結果】