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();
开发者_如何学JAVA foreach(Process pr in prs)
{
if(pr.ProcessName == "****ProcessName")
pr.Kill();
}
}
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.
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();
Note that LINQ is for querying, projecting and aggregating. You are doing something with a side effect here and LINQ isn't appropriate for that. So, I separate the query part away from the side effecty part.
private void KillProcessesWithName(string processName) {
var processesToKill = Process.GetProcesses()
.Where(p => p.ProcessName == processName);
foreach(var process in processesToKill) {
process.Kill();
}
}
It is arguable whether or not the LINQified version is better and I would keep it as is.
IEnumerable doesn't have a ForEach extension method so you can't fully 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();
}
var processes = from process in Process.GetProceeses()
where process.ProcessName == "****ProcessName"
select process;
foreach(var p in processes){
p.Kill()
}
I think the List has an ForEach-extension you could use.
Process.GetProcesses().Where(p=>p.ProcessName==whatever).ToList().ForEach(y => y.Kill);
精彩评论