2008-11-07 VB.Net 如何過濾重複的陣列元素 16794 0 VB.Net / C#.Net / 摘要:VB.Net 如何過濾重複的陣列元素 如何過濾重複的陣列元素<< VB.Net 2005 >> Private Sub Button1_Click(ByVal s As Object, ByVal e As EventArgs) Handles Button1.Click ' 一整數陣列 Dim ary() As Integer = {1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3} ary = DistinctArray(ary) ' 過濾重複的陣列元素 For Each i As Integer In ary ' 底下顯示過濾後的陣列 MessageBox.Show(i) Next End Sub Private Function DistinctArray(ByRef Ary() As Integer) As Integer() ' 使用 List 泛型類別 Dim lst As New List(Of Integer) ' 用 Contains 方法,判斷某元素是否在 List 中,不存在則新增進 List 中。 For Each i As Integer In Ary If Not lst.Contains(i) Then lst.Add(i) Next Return lst.ToArray ' 將 List 的元素複製到新的陣列並回傳 End Function<< VB.Net 2008 >> ' 方法 1 Private Sub Button1_Click(ByVal s As Object, ByVal e As EventArgs) Handles Button1.Click Dim ary() As Integer = {1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3} ' 使用預設的相等比較子來比較值,以便從序列傳回獨特的項目。 For Each i As Integer In ary.Distinct.ToArray() MessageBox.Show(i) Next End Sub ' 方法 2 Private Sub Button2_Click(ByVal s As Object, ByVal e As EventArgs) Handles Button2.Click Dim ary() As Integer = {1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3} 'IEnumerable 泛型介面 Dim ienum As IEnumerable(Of Integer) = ary ' Enumerable類別.Distinct 方法移除重複項目的序列 For Each i As Integer In ienum.Distinct MessageBox.Show(i) Next End Sub 回首頁