user393014
user393014

Reputation: 475

Get string[] or process id's from process[] using LINQ

I have opened five notepad.exe's. Now I want to know all the process id's associated with each notepad.exe.

I know I can retrieve list of notepad processes by:

Process[] processes = Process.GetProcessesByName("notepad");

But now I want string[] of process Id's of those notepad instances using LINQ. How do I do that? I know i can create string[] and using foreach loop populate the string[] but I would like to know using LINQ.

Upvotes: 1

Views: 3762

Answers (5)

Dan Abramov
Dan Abramov

Reputation: 268215

Most answers concentrate on creating string [] out of Process [].
But why do you need an array at all?

If all you need to do is to loop through all items later, you don't really need to allocate memory for another array. Instead, use IEnumerable<T> returned by Select.

var ids = Process
    .GetProcessesByName("notepad")
    .Select(process => process.Id); // returns IEnumerable<int>

foreach (var id in ids)
    DoSomethingWith (id);

You can select string representations the same way, or you could project ids as well:

var stringIds = ids.Select (id => id.ToString ()); // returns IEnumerable<string>

Upvotes: 1

SLaks
SLaks

Reputation: 887215

You can write

var ids = Array.ConvertAll(Process.GetProcessesByName("notepad"), p => p.Id);

This will be (slightly) faster than Select and ToArray, since it won't need to resize the array.

If you can use an IEnumerable<int> instead of an array, Select (without ToArray) will be faster.

Upvotes: 6

BrokenGlass
BrokenGlass

Reputation: 160852

You could do a one-liner using array conversion instead of LINQ:

int[] processIds = Array.ConvertAll(Process.GetProcessesByName("notepad"), 
                                    p => p.Id);

To get a list of process ids:

Process[] processes = Process.GetProcessesByName("notepad");
var processIdList = processes.Select(p => p.Id).ToList();

To get an array instead of a list you can do:

var processIdList = processes.Select(p => p.Id).ToArray();

Note that the process Id is of type int. If you wanted a list of strings instead you could just do this:

var processIdList = processes.Select(p => p.Id.ToString()).ToArray();

Upvotes: 4

Bryan Watts
Bryan Watts

Reputation: 45445

var ids = Process
    .GetProcessesByName("notepad")
    .Select(process => process.Id)
    .ToArray();

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564333

You can use:

Process[] processes = Process.GetProcessesByName("notepad");
string[] ids = processes.Select(p => p.Id.ToString()).ToArray();

However, I question the need to put this into a string[] type. It might be better to just leave the Process.Id values as integers:

Process[] processes = Process.GetProcessesByName("notepad");
var ids = processes.Select(p => p.Id);
foreach(int processId in ids)
{
   // Do something with each processId
}

Upvotes: 3

Related Questions