Using LINQ to Find Top 5 Processes that are Consuming Memory

A user on a forum recently asked me how to find the processes that were currently running. A quick look at MSDN led me to the Process object. The Process provides access to local and remote processes and enables you to start and stop local system processes. Here’s how to find out the top five processes that are consuming memory.

C#

var query = (from p in System.Diagnostics.Process.GetProcesses()
orderby p.PrivateMemorySize64 descending
select
p)
.Skip(0)
.Take(5)
.ToList();
foreach (var item in query)
{
System.Diagnostics.Debug.WriteLine(item.ProcessName);
}

VB.NET

Dim query = ( _
From p In System.Diagnostics.Process.GetProcesses() _
Order By p.PrivateMemorySize64 Descending _
Select p).Skip(0).Take(5).ToList()
For Each item In query
System.Diagnostics.Debug.WriteLine(item.ProcessName)
Next item

The code above produces the following results on my computer:

clip_image002






About The Author

Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET and regular presenter at conferences and user groups throughout Australia. Being an ASP.NET Insider, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with JavaScript. He also blogs regularly at DotNetCurry.com. Follow him on twitter @malcolmsheridan

1 comment:

Anonymous said...

Dont need the Skip(0)

Also can do like this:
var query = System.Diagnostics.Process.GetProcesses().OrderByDescending(p=> p.PrivateMemorySize64).Take(5).ToList();