Jaa


Linq Everywhere: Kill processes

For some test code I needed to write a small utility that kills all processes running that matches a given name. Like KillApp Devenv.

After writing the code as I normally would, I thought I should Linquify it. So here what I cooked up

     static class Program
    {
        static void Main(string[] args)
        {
            if (args.Length < 1 || args[0] == "-?")
            {
                Console.WriteLine("Usage: KillApp ");
                return;
            }

             (from p in Process.GetProcesses()<br>                    where p.ProcessName.Contains(args[0])<br>                    select p).ForEach(p => p.Kill()); 

        }

        public static void ForEach<T>(this IEnumerable<T> list, Action<T> act)
        {        
            foreach (T t in list)
                act(t);
        }

    }

Sheer beauty. The only glitch was that I had to write a ForEach extension method :( .

Since I never liked DB's a lot (that doesn't include our test manager Dinesh Bhat though) I converted the Linq query to extension method style as in

 Process.GetProcesses().Where(p=>p.ProcessName.Contains(args[0])).ForEach(p=>p.Kill());

Thats when I started wondering is this Lisp I'm coding in or C#? Then the order of the parenthesis reminded me it is indeed C#. With Linq life is good :) the only thing that can make me

Comments

  • Anonymous
    February 15, 2007
    The comment has been removed
  • Anonymous
    February 15, 2007
    from most C# developers is a- but for people moving into C# from DB background its A++In some scneariopThis is a sample and I cut pasted code from a tool. We have much more elaborate handling there including all processes specified in the args and switches to say use window title and not process name
  • Anonymous
    February 15, 2007
    The comment has been removed
  • Anonymous
    February 15, 2007
    I'm not sure I'd go A++ for DB background people (considering myself one of them).In the VB syntax for LINQ (Dim waCusts = Select c.Name, c.City From c In custs Where c.State = “WA”), where the order matches that of sql (select .. from .. where ..) I think it's A++, but C# went the route of reordering (AFAICT mainly for the intellisense benefits during the writing of the query), so I think it's still a bit to grok for most sql devs.
  • Anonymous
    February 15, 2007
    Ok I updated the code with the &gt; &lt; escaping.
  • Anonymous
    February 16, 2007
    List<T> already has a ForEach that takes an Action<T>.I would have preferred it being on IEnumerable<T>.
  • Anonymous
    February 17, 2007
    The code is good, and I appreciate the thought of using linq but I'd also like to know what was missing from the command taskkill.exe (with a bit of cmd magic thrown in) or as jmanning mentioned - powershell.
  • Anonymous
    February 18, 2007
    kfarmer you can use All<T> if you are OK with using Action<T>.