user3848640
user3848640

Reputation: 57

How do I check if a member of an array matches any member of another array using Linq?

I need to continuously check whether one of a number of processes is running. So far I've used:

Process[] Processes = Process.GetProcesses();

to get the currently running processes. I have a string array containing the list of processes I want to make sure aren't running before I continue:

string[] ProcessesToCheck = new string[] {"Chartvue",
        "collvue"
        ,"damage"
        ,"Datagen"
        ,"datagenlegacy"
        ,"FAST_SACS"
        ,"hullmesher"
        ,"hullmodeler"
        ,"ifatigue"};

The question is, how to I check that all ProcessName members of Processes does not contain any member of ProcessesToCheck?

Upvotes: 2

Views: 111

Answers (2)

Christos
Christos

Reputation: 53958

You could try something like this:

var isExists = Processes.Any(x => ProcessesToCheck.Contains(x.ProcessName));

In the above code we use the method Any to see if there exists at least one process in the array Processes, whose property called ProcessName is contained in the array called ProcessesToCheck.

For more information about Any, please have a look here and for more information about Contains, please have a look here.

Upvotes: 2

Selman Genç
Selman Genç

Reputation: 101732

You can get the process names into an hashset (for a faster lookup) then use Any method to check if any of the process names is present in ProcessesToCheck

var processNames = new HashSet<string>(Processes.Select(p => p.ProcessName));
bool isExists = ProcessesToCheck.Any(processNames.Contains);

Upvotes: 3

Related Questions