using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LinqDemo
{
public class ProcessData
{
public int id { get; set; }
public string Name { get; set; }
public Int64 Memory { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Xml;
using System.Diagnostics;
namespace LinqDemo
{
class Program
{
static void Main(string[] args)
{
}
public static void LambdaDemoGeneral()
{
var process = new List<ProcessData>();
foreach(var pro in Process.GetProcesses())
{
if(pro.WorkingSet64>=20*1000*1000)
{
process.Add(new ProcessData {id=pro.Id,Name=pro.ProcessName,Memory=pro.WorkingSet64});
}
}
Array.ForEach(process.ToArray(), c => Console.Write("id为:" + c.id + "进程名为:" + c.Name + "进程大小为:" + c.Memory + "\n"));
}
public static bool Filter(Process process)
{
return process.WorkingSet64 >= 20 * 1000 * 1000;
}
public static void LambdaDemoDelegate(Predicate<Process> match)
{
var process = new List<ProcessData>();
foreach (var pro in Process.GetProcesses())
{
if (match(pro))
{
process.Add(new ProcessData { id = pro.Id, Name = pro.ProcessName, Memory = pro.WorkingSet64 });
}
}
Array.ForEach(process.ToArray(),c=>Console.Write("id为:"+c.id+"进程名为:"+c.Name+"进程大小为:"+c.Memory+"\n"));
}
//委托的使用
public static void DelegateDemo()
{
LambdaDemoDelegate(Filter);
}
//匿名委托的使用
public static void NoNameDelegateDemo()
{
LambdaDemoDelegate(delegate(Process process){return process.WorkingSet64>=20*1000*1000});
}
//lambda表达式的使用
public static void LambdaDemo()
{
LambdaDemoDelegate(process=>process.WorkingSet64>=20*1000*1000);
}
}
}
测试结果:
------ Test started: Assembly: LinqDemo.exe ------
id为:1804进程名为:explorer进程大小为:22355968
id为:3096进程名为:SoftMgrLite进程大小为:30908416id为:432进程名为:sqlservr进程大小为:20783104id为:1944进程名为:sqlservr进程大小为:50274304id为:2228进程名为:TheWorld进程大小为:63655936id为:2572进程名为:AcroRd32进程大小为:40710144id为:500进程名为:wandoujia_helper进程大小为:57176064id为:308进程名为:AcroRd32进程大小为:20774912id为:2080进程名为:searchindexer进程大小为:20176896id为:1100进程名为:svchost进程大小为:27500544id为:5464进程名为:ProcessInvocation86进程大小为:28516352id为:648进程名为:OrayRemoteService进程大小为:34111488id为:3988进程名为:devenv进程大小为:124190720id为:3868进程名为:TheWorld进程大小为:91607040id为:5180进程名为:WebDev.WebServer进程大小为:62074880id为:2772进程名为:QQ进程大小为:30638080id为:5524进程名为:TheWorld进程大小为:438681601 passed, 0 failed, 0 skipped, took 0.75 seconds (Ad hoc).
以上几个实例,从当前进程中筛选出运行内存大于等于20MB的进程,使用了几种方法,一般方法,委托,匿名委托,lambda表达式。