Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two ArrayList Contents using c#

I have two arraylist. Namely ExistingProcess and CurrentProcess.

The ExistingProcess arraylist contains the list of process that was running when this application started.

The CurrentProcess arraylist is in a thread to fetch the process running in the system all the time.

Each time the currentProcess arraylist gets the current process running, i want to do a compare with ExistingProcess arraylist and show in a messagebox like,

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

Basically this is a comparison of two arraylist to find out the new process started and process closed after my C# application is launched.

like image 504
Anuya Avatar asked Dec 29 '22 09:12

Anuya


2 Answers

You could use LINQ Except.

Except produces the set difference of two sequences.

For samples:

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

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

Code to illustrate the idea...

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());
}
like image 79
Leniel Maccaferri Avatar answered Jan 11 '23 14:01

Leniel Maccaferri


First, go over the first list and remove each item from the second list. Then vice versa.

    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 );

After that, the first list will contain all the missing processes, and the second - all new processes.

like image 37
Fyodor Soikin Avatar answered Jan 11 '23 15:01

Fyodor Soikin