2013-04-24 88 views
2

我必須編寫代碼才能獲得所有可訪問的進程,但是我需要刪除此數組上的重複項,並且每個進程只顯示一次。使用VB去除進程數組中的重複項.net

如何做到這一點的最佳方法,因爲我認爲進程數組不像普通數組。

我的代碼:

For Each p As Process In Process.GetProcesses 
    Try 
     'MsgBox(p.ProcessName + " " + p.StartTime.ToString) 
    Catch ex As Exception 
     'Do nothing 
    End Try 
Next 

預先感謝

+0

爲什麼你認爲它不是一個正常的數組? 「類型爲Process的**數組**,代表在本地計算機上運行的所有進程資源。」 [Process.GetProcesses方法](http://msdn.microsoft.com/en-us/library/1f3ys1f9.aspx) – Tim 2013-04-24 21:20:22

回答

4

Process.GetProcesses()方法返回一個數組。您可以使用Distinct方法,爲其提供IEqualityComparer

一個例子是作爲比較器:

Public Class ProcessComparer 
    Implements IEqualityComparer(Of Process) 

    Public Function Equals1(p1 As Process, p2 As Process) As Boolean Implements IEqualityComparer(Of Process).Equals 
     ' Check whether the compared objects reference the same data. 
     If p1 Is p2 Then Return True 
     'Check whether any of the compared objects is null. 
     If p1 Is Nothing OrElse p2 Is Nothing Then Return False 
     ' Check whether the Process' names are equal. 
     Return (p1.ProcessName = p2.ProcessName) 
    End Function 

    Public Function GetHashCode1(process As Process) As Integer Implements IEqualityComparer(Of Process).GetHashCode 
     ' Check whether the object is null. 
     If process Is Nothing Then Return 0 
     ' Get hash code for the Name field if it is not null. 
     Return process.ProcessName.GetHashCode() 
    End Function 
End Class 

而且你可以使用它像這樣:

Sub Main() 
    Dim processes As Process() = Process.GetProcesses() 
    Console.WriteLine(String.Format("Count before Distinct = {0}", processes.Length)) 

    ' Should contain less items 
    Dim disProcesses As Process() = processes.Distinct(New ProcessComparer()).ToArray() 
    Console.WriteLine(String.Format("Count after Distinct = {0}", disProcesses.Length)) 

    Console.ReadLine() 
End Sub 

你很可能得比較程序細化到您的規格和你的情況會使用它。

+0

完美!謝謝! – jgiunta 2013-04-24 22:05:36