【问题标题】:Compare two ArrayList Contents using c#使用 c# 比较两个 ArrayList 内容
【发布时间】:2011-03-27 15:00:44
【问题描述】:

我有两个数组列表。即ExistingProcess和CurrentProcess。

ExistingProcess 数组列表包含此应用程序启动时正在运行的进程列表。

CurrentProcess 数组列表在一个线程中,用于获取系统中一直运行的进程。

每次 currentProcess arraylist 让当前进程运行时,我想与 ExistingProcess arraylist 进行比较并显示在消息框中,例如,

Missing process : NotePad [If notepad is closed and the application is launched]
New Process : MsPaint [if MSPaint is launched after the application is launched]

基本上这是两个arraylist的比较,以找出在我的C#应用程序启动后启动的新进程和关闭的进程。

【问题讨论】:

    标签: c# comparison arraylist


    【解决方案1】:

    您可以使用 LINQ 除外。

    除了产生两个的集合差 序列。

    对于样品:

    http://msdn.microsoft.com/en-us/library/bb300779.aspx

    http://msdn.microsoft.com/en-us/library/bb397894%28VS.90%29.aspx

    代码来说明这个想法...

    static void Main(string[] args)
    {
        ArrayList existingProcesses = new ArrayList();
    
        existingProcesses.Add("SuperUser.exe");
        existingProcesses.Add("ServerFault.exe");
        existingProcesses.Add("StackApps.exe");
        existingProcesses.Add("StackOverflow.exe");
    
        ArrayList currentProcesses = new ArrayList();
    
        currentProcesses.Add("Games.exe");
        currentProcesses.Add("ServerFault.exe");
        currentProcesses.Add("StackApps.exe");
        currentProcesses.Add("StackOverflow.exe");
    
        // Here only SuperUser.exe is the difference... it was closed.   
        var closedProcesses = existingProcesses.ToArray().
                              Except(currentProcesses.ToArray());
    
        // Here only Games.exe is the difference... it's a new process.   
        var newProcesses = currentProcesses.ToArray().
                           Except(existingProcesses.ToArray());
    }
    

    【讨论】:

    • 您的代码将内容与其确切的数组位置匹配。但我想互相检查一下。因为当我与进程名称进行比较时,顺序可能会有所不同。
    • 作为实现代码的结果,它将所有内容显示为新进程,并将所有内容显示为已关闭进程。因为它一对一地检查。它不应该是这样的。对吗?
    • 项目的顺序不会影响结果。据我了解,这正是您所需要的。它会为您提供两个列表:1 个用于关闭的流程,1 个用于新流程。
    【解决方案2】:

    首先,检查第一个列表并从第二个列表中删除每个项目。然后反之亦然。

        var copyOfExisting = new ArrayList( ExistingProcess );
        var copyOfCurrent = new ArrayList( CurrentProcess );
    
        foreach( var p in ExistingProcess ) copyOfCurrent.Remove( p );
        foreach( var p in CurrentProcess ) copyOfExisting.Remove( p );
    

    之后,第一个列表将包含所有缺失的进程,第二个列表将包含所有新进程。

    【讨论】:

    • 你能告诉我如何在消息框中打印 Missing 和 new 进程吗?谢谢。
    • 这取决于你的环境是什么以及你使用什么GUI。
    猜你喜欢
    • 1970-01-01
    • 2013-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-25
    • 1970-01-01
    相关资源
    最近更新 更多