[转载]利用Linq写简洁代码 – 老衲爱封装 – 博客园.
1.xml读写
d盘下有Demo.xml,内容如下
<?xml version="1.0" encoding="utf-8" ?> <Earthworm> <Demo> <Aspect name=""> <Advice type="before" assembly="" className=""> <MethodName>asd</MethodName> <MethodName>kll</MethodName> </Advice> <Advice type="stop" assembly="" className=""> <MethodName></MethodName> <MethodName></MethodName> </Advice> <Advice type="after" assembly="" className=""> <MethodName></MethodName> <MethodName></MethodName> </Advice> </Aspect> </Demo> </Earthworm>
现在想获取type为before的所有MethodName的节点值
普通读取方法
XmlDocument xmldoc = new XmlDocument(); xmldoc.Load(@"d:\demo.xml"); XmlNodeList nodelist = xmldoc.SelectNodes("Earthworm/Demo/Aspect/Advice[@type='before']/MethodName"); foreach (XmlNode node in nodelist) { Console.WriteLine(node.InnerText); }
Linq To Xml 读取方法
var dname = from k in (from m in XDocument.Load("d:\\zhongming.xml").Descendants("Advice") where m.Attribute("type").Value == "before" select m).Descendants("MethodName") select k.Value;//一句话搞定,很给力 foreach (var a in dname) { Console.WriteLine(a); }
2.查找普通对象
有如下数组:
int[] data = new int[] {12,23,445,666,777,90,33,2,0,-89 };
想查找大于50的对象
普通方法
var findObjects = new List<int>(); foreach (int i in data) { if (i > 50) { findObjects.Add(i); } }
Linq方法
var findObjects=from d in data where d>50 select d;//同样是一句话
3.查找动态对象
class People { /// <summary> /// 姓名 /// </summary> public string Name{get;set;} /// <summary> /// 年龄 /// </summary> public int Age{get;set;} /// <summary> /// 性别 /// </summary> public bool Gender { get; set; } }
有如下数据
People[] data = new People[] { new People{Name="西门吹雪",Gender=true,Age=1200}, new People{Name="令狐冲",Gender=true,Age=999}, new People{Name="任盈盈",Gender=false,Age=456}, new People{Name="欧阳锋",Gender=true,Age=9999}, new People{Name="黄药师",Gender=true,Age=670}, new People{Name="吴世龙",Gender=true,Age=25}};
想查找所有的People的姓名和年龄
普通方法
必须建造一个结构体或类,用来存储姓名和年龄,结构体如下
struct DynamicObject { public string Name; public int Age; }
然后查找
List<DynamicObject> objs = new List<DynamicObject>(); foreach (People p in data) { objs.Add(new DynamicObject { Name = p.Name, Age = p.Age }); }
linq方法
var objects = from d in data select new { d.Name, d.Age };
还有更牛的是优化过程
比如那个读xml的你是这样写的
var doc = XDocument.Load(@"d:\demo.xml"); var list=from m in doc.Descendants("Advice") where m.Attribute("type").Value == "before" select m; var datas=from k in list.Descendants("MethodName") select k.Value; foreach (var a in datas) { Console.WriteLine(a); }
编译完成之后,拿一Reflector看,是这个样子的
IEnumerable<string> datas = from k in (from m in XDocument.Load(@"d:\demo.xml").Descendants("Advice") where m.Attribute("type").Value == "before" select m).Descendants<XElement>("MethodName") select k.Value;//变成一句了哦 foreach (string a in datas) { Console.WriteLine(a); }
就讲这么多,其他的一起探索吧