Linq语句和Lambda是Framework3.5的新特性,最近学了一段时间,自己做一个小的总结。
1.Linq,Lambda查数组:
String[] name = new string[] { "aaaaa", "dddd", "ssss", "ffff", "eee", "wwwwwwwwwww", "qqqqqqqq" };
Linq语句: IEnumerable<String> result = from s in name where s.Length > 4 select s;
Lambda表达式:IEnumerable<String> result = name.Where(s=>s.Length>4).OrderBy(s=>s).Select(s=>s);
或者: Func<String, bool> where= s => s.Length >= 5;
Func<String, String> orderBy= s => s;
Func<String, String> select = s => s;
注(Func<XXX,XXX>是一个函数式委托类型)
IEnumerable<String> result = name.Where(where).OrderBy(orderBy).Select(select);
注(这里的s是给数组的元素起的一个别名)
List<String> lt = result.ToList();
下面是一个查询简单通用方法:
public static IEnumerable<T> where<T>(IEnumerable<T> source, Func<T, bool> exp)
{
foreach (T item in source)
{
if (exp(item))
{
yield return item;
}
}
}
2.Linq,Lambda查数集合:
先添加一个学生类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LinqTest
{
public class Student
{
public Student(int sid,String sname)
{
this.sid = sid;
this.sname = sname;
}
private int sid;
public int Sid
{
get { return sid; }
set { sid = value; }
}
private String sname;
public String Sname
{
get { return sname; }
set { sname = value; }
}
}
}
List<Student> list = new List<Student>() { new Student(1, "张三"),
new Student(2, "李四"), new Student(3, "王五") };
往集合里添加三个对象。
Linq语句: IEnumerable<Student> result = from s in list where s.Sid > 1 select s;
Lambda表达式:IEnumerable<Student> result = list.Select(s => s).Where(s => s.Sid > 1);
List<Student> lt = result.ToList();
1.Linq,Lambda查数数据库表:
(1)先做一个表到实体之间的映射
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Da
using System.Da
namespace LinqTest
{
[Table(Name = "t_user")]
public class UserCLR
{
[Column (DbType="int not null",IsPrimaryKey=true)]
private int uid;
public int Uid
{
get { return uid; }
set { uid = value; }
}
[Column (DbType="varchar(50) not null")]
private String uname;
public String Uname
{
get { return uname; }
set { uname = value; }
}
[Column(DbType = "varchar(50) not null")]
private String upass;
public String Upass
{
get { return upass; }
set { upass = value; }
}
}
}
(2)写数据访问层的DALusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Da
namespace LinqTest
{
public class UserDAL
{
private const String ConnString=@"database=zf;uid=sa;pwd=123";
public static List<UserCLR> GetUser()
{
DataContext dc = new DataContext(ConnString);
Table<UserCLR> user = dc.GetTable<UserCLR>();
//(Linq语句查询)IEnumerable<UserCLR> result= from s in user select s;(Linq语句查询)
//Lambda表达式查询:
Func<UserCLR, bool> where = s => s != null;
IEnumerable<UserCLR> result= user.Select(s => s).Where(where);
List<UserCLR> lt = result.ToList();
return lt;
}
}
}