简体   繁体   中英

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.

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.

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

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
}
var ids = Process
    .GetProcessesByName("notepad")
    .Select(process => process.Id)
    .ToArray();

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM