tags:

views:

60

answers:

1

Hi,

I have a List of string objects which represent process names. I want to filter a collection of running Processes (retrieved by using GetProcesses()), by using the list of string objects I have. So if I want to look for the Sql Server process running in the processes collection, I will look for the string name as stored in the string list.

How can I filter a list of processes to get only the processes which have the same process names as a list of strings (the different generic types makes it hard - for me, anyway)?

I am using .NET 4.0 and LINQ.

Thanks

+1  A: 

This should do it..

var targetNames = new [] { "processone", "Processtwo" };

var processes = from p in Process.GetProcesses()
                where targetNames.Any(n => n == p.ProcessName)
                select p;
Sam
Close. ProcessName will not include ".exe" so the `targetNames` shouldn't. If the OP isn't using the proper case the comparison should be case-insensitive: `n => n.Equals(p.ProcessName, StringComparison.InvariantCultureIgnoreCase)`.
Ahmad Mageed
That works perfectly, thanks!
dotnetdev
.Intersect() would be a better choice than .Any() here.
Joel Coehoorn