最近在看linqtosql,这里就当做笔记本了吧!
隐含类型局部变量
1 先介绍隐含类型局部变量2 var age=18;3 var username="冰雪乾坤";4 var userlist=new[] { "a","b","c"}5 foreach(var user in userlist)6 {7 console.writeline(user);8 }
匿名类型
匿名类型
1 var data=new {username="冰雪乾坤",age=18}2 console.writeline("username:{0} age:{1}",data.username,data.age);3 这里的var 是懒人类型,我们不需要管他是什么类型,他将会自我匹配
扩展方法
1 public static calss helper 2 { 3 public static string MDHash(this string s) 4 { 5 return system.web.security.formsauthentication.hashPasswordforstoringinconfigfile(s,"md5") 6 } 7 8 public static bool In(this object o,IEnumerable b) 9 {10 foreach(object obj in b)11 {12 if(obj==o)13 {14 return true;15 }16 return false;17 }18 }19 // diaoyong kuozhan20 console.writeline("123456".D5Hash());21 console.writeline("1".In(new[]{ "1","2","3"}));22 }
1 Public calss person 2 { 3 public string username{ get;protect set;} 4 public int age{ get;set;} 5 public Person() 6 { 7 this.username="冰雪乾坤"; 8 } 9 }10 Person p=new Person();11 console.writeline(p.username);
对象初始化器
1 public class Person 2 { 3 public string username{ get;set;} 4 public int age{ get;set;} 5 public override stringToString() 6 { 7 return string.Format("username:{0} age{1}",this.username,this.age 8 } 9 }10 11 12 Person p=new Person(){username="qiankun",age=18}13 console.writeline(p.tostring());14 编译器会自动为你做setter操作,使得原本几行的属性赋值操作能在一行中完成。这里需要注意:15 16 l 允许只给一部分属性赋值,包括internal访问级别17 18 l 可以结合构造函数一起使用,并且构造函数初始化先于对象初始化器执行
list init
1 public class Person 2 3 { 4 5 public string username { get; set; } 6 7 public int age { get; set; } 8 9 10 11 public override string ToString()12 13 {14 15 return string.Format("username:{0} age:{1}", this.username, this.age);16 17 }18 19 } 20 21 22 var persons =new list{ 23 new Person{username="q",age=18},24 new Person{username="a",age=18}25 }26 27 foreach(var p in persons)28 {29 console.WriteLine(ptostring);30 }
Lambda表达式
1 var list =new [] { "aa","bb","ac"};2 var resoult = Array.FindAll(list,s=>(s.IndexOf("a")>-1));3 4 foreach(var v in result)5 {6 Console.WriteLine(v);7 }
复杂的例子
1 public delegate int mydog(int a,int b); 2 3 public static class LambdaTest 4 { 5 public static int opr(this int a,int b,mydg dg) 6 { 7 return dg(a,b); 8 } 9 }10 11 12 Console.WriteLine(1.oper(2,(a,b)=>a+b));13 Console.WriteLine(2.oper(1,(a,b)=>a+b));
查询
1 var persons=new List{ 2 new Person{username="A",age=18}, 3 new Person {username="B",age=20}, 4 new Person {username="C",age=22} 5 }; 6 7 var selectperson =from p in persons 8 where p.age>=21 9 select p.username.ToUpper();10 foreach(var p in selectperson)11 {12 console.writeLine(p);13 }
等价于
var selectperson=persons.where(p=>p.age>=21).select(p=>p.username.ToUpper());