How / could you rewrite this as Linq?

I am doing this and I am just wondering how am I new to all of this if Linq can be used to rewrite this?

private void checkacrobat() { Process[] prs = Process.GetProcesses(); foreach(Process pr in prs) { if(pr.ProcessName == "****ProcessName") pr.Kill(); } } 
+4
source share
6 answers
 foreach(var process in Process.GetProcesses().Where(p=>p.ProcessName==whatever)) process.Kill(); 

Remember, use instructions for actions such as killing a process. Use LINQ for queries that read values ​​without changing them.

But your code reads great as it is. I would not change it without a good reason.

+7
source

In the method syntax:

 var processesToBeKilled = Process.GetProcesses() .Where(pr => pr.ProcessName == "****ProcessName"); foreach(var process in processesToBeKilled) process.Kill(); 

In the query syntax:

 var processesToBeKilled = from pr in Process.GetProcesses() where pr.ProcessName == "****ProcessName" select pr; foreach(var process in processesToBeKilled) process.Kill(); 

Assigned Method:

There is no need for LINQ; there is already a convenient Process.GetProcessesByName method:

 var processesToBeKilled = Process.GetProcessesByName("****ProcessName"); foreach(var process in processesToBeKilled) process.Kill(); 
+5
source

Please note that LINQ is for querying, projecting, and aggregating. You are doing something with a side effect here, and LINQ is not suitable for this. So, I separate the request part from the side effective part.

 private void KillProcessesWithName(string processName) { var processesToKill = Process.GetProcesses() .Where(p => p.ProcessName == processName); foreach(var process in processesToKill) { process.Kill(); } } 

Perhaps the LINQified version is better, and I would keep it as it is.

+2
source

IEnumerable does not have a ForEach extension method, so you cannot completely rewrite it as LINQ (unless you use your own ForEach extension)

 Process[] processes in Process.GetProcesses(); foreach(Process pr in processes.Where(p => p.ProcessName == "****ProcessName")) { pr.Kill(); } 
+1
source
 var processes = from process in Process.GetProceeses() where process.ProcessName == "****ProcessName" select process; foreach(var p in processes){ p.Kill() } 
+1
source

I think there is a ForEach extension on the list that you could use.

 Process.GetProcesses().Where(p=>p.ProcessName==whatever).ToList().ForEach(y => y.Kill); 
+1
source

All Articles