使用LINQ从process []获取string []或进程id

use*_*014 1 c# linq string

我打开了五个notepad.exe.现在我想知道与每个notepad.exe相关的所有进程ID.

我知道我可以通过以下方式检索记事本进程列表:

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

但是现在我想要使用LINQ的那些记事本实例的进程Id的字符串[].我怎么做?我知道我可以创建string []并使用foreach循环填充字符串[]但我想知道使用LINQ.

SLa*_*aks 6

你可以写

var ids = Array.ConvertAll(Process.GetProcessesByName("notepad"), p => p.Id);
Run Code Online (Sandbox Code Playgroud)

这将(稍微)快于SelectToArray,因为它不需要调整数组的大小.

如果你可以使用IEnumerable<int>而不是数组,Select(没有ToArray)会更快.