Vaibhav Jain
Vaibhav Jain

Reputation: 34447

Need help in Linq

I am writing a Linq query just for learning.

    var result = Process.GetProcesses()
                .Where(p => p.WorkingSet64 > 20 * 1024 * 1024)
                .OrderByDescending(p => p.WorkingSet64)
                .Select(p => new {p.Id,p.ProcessName,p.WorkingSet64 });

I want to iterate in to result

 foreach(process in result) //error-type or namespace process could not be found.
            {
                Console.WriteLine(Process.ProcessName);
            }

I want to iterate in to result and print each process name on the console.

What I am doing wrong.

Upvotes: 0

Views: 133

Answers (4)

Allon Guralnek
Allon Guralnek

Reputation: 16131

Consider using LINQ's query syntax for terser code:

var result = from p in Process.GetProcesses()
             where p.WorkingSet64 > 20 * 1024 * 1024
             orderby p.WorkingSet64 descending
             select new { p.Id, p.ProcessName, p.WorkingSet64 };

Then, instead of a loop, think in LINQ to do the same thing:

Console.WriteLine(string.Join("\r\n", result.Select(p => p.ProcessName)));

EDIT: The overload of string.Join() used above was only introduced in .NET 4.0. To use an overload that is available in earlier versions, which accepts a string[] rather than an IEnumerable<string>, just chain a .ToArray() after the .Select():

Console.WriteLine(string.Join("\r\n", result.Select(p => p.ProcessName).ToArray()));

Upvotes: 1

DixonD
DixonD

Reputation: 6638

Are you declared process before loop? If not you should change your for each to

foreach(var process in result)
{
    Console.WriteLine(process.ProcessName);
}

Upvotes: 1

Stephan Keller
Stephan Keller

Reputation: 1633

You could also project your query into a list of processes:

List<Process> result = Process.GetProcesses()
              .Where(p => p.WorkingSet64 > 20 * 1024 * 1024)
              .OrderByDescending(p => p.WorkingSet64).ToList();

foreach(Process process in result) 
{
  Console.WriteLine(process.ProcessName);
}

Upvotes: -1

Jon
Jon

Reputation: 16726

you're close:

foreach (var process in result) {
    Console.WriteLine(process.ProcessName);
}

(I'm assuming you haven't declared the name process before.)

Also note that if you use process (with a small p) in the foreach line, you need to keep the same case when you use it inside the loop.

Upvotes: 8

Related Questions