Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How/ could you rewrite this as Linq?

Tags:

c#

linq

I'm doing this and was just wondering as I'm new to all of this if Linq could be used to rewrite this?

private void checkacrobat()
{
    Process[] prs = Process.GetProcesses();
    foreach(Process pr in prs)
    {
         if(pr.ProcessName == "****ProcessName")
              pr.Kill();
    }
}
like image 392
RTFS Avatar asked Dec 03 '22 10:12

RTFS


2 Answers

foreach(var process in Process.GetProcesses().Where(p=>p.ProcessName==whatever))
    process.Kill();

Remember, use statements for actions like killing a process. Use LINQ for queries, that read values without changing them.

But your code is perfectly readable as it is. I wouldn't change it without a good reason.

like image 69
Eric Lippert Avatar answered Dec 06 '22 00:12

Eric Lippert


In method syntax:

var processesToBeKilled = Process.GetProcesses()
                                 .Where(pr => pr.ProcessName == "****ProcessName");

foreach(var process in processesToBeKilled)
   process.Kill();

In query syntax:

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

foreach(var process in processesToBeKilled)
   process.Kill();

Purpose-built method:

There's really no need for LINQ here; there's already the handy Process.GetProcessesByName method:

var processesToBeKilled = Process.GetProcessesByName("****ProcessName");

foreach(var process in processesToBeKilled)
   process.Kill();
like image 35
Ani Avatar answered Dec 06 '22 00:12

Ani