落后就要挨打,05年Preview的玩意,好久前就开始看,一直没写过,写了才感觉真的爽
C#3.5出现了很多新特性,比如隐式类型本地变量,匿名类型,Lambda表达式,扩展方法,查询综合,宽松委托,自动实现属性,分部方法等.还是用代码来说明问题吧(只关心与Linq关系紧密的部分):
//实体,为了oo,将关系型数据库转化为实体对象
[Table (Name="Post")]
public class PostInfo
{
[Column(Name = "uid")] public int uid { get; set; }
[Column(Name = "pid")] public int pid { get; set; }
[Column(Name = "p_content")] public string p_content { get; set; }
}

public class UserInfo
{
//更方便的属性访问器,自动实现属性
public int uid {get;set;}
public string username {get;set;}
public string password {get;set;}
public string intro {get;set;}
}

//隐式类型本地变量
var test="First Test";
Response.Write(test);
//对象和集合初始值设定项
var list = new List() { "
", "LinQ ", "を ", "よく ", "勉強したいです。", "
" };
foreach (var tmp in list) Response.Write(tmp);
var user = new UserInfo{uid=1,username="Lee",intro="Just Test"};
Response.Write("ID:" + user.uid + "
" + "名前:" + user.username + "
");
//对象和集合初始值设定项
var userlist = new[]
{
new UserInfo{uid=2,username="zhang",intro="hi"},
new UserInfo{uid=3,username="wang",intro="test"},
new UserInfo{uid=4,username="chen",intro="linq"},
};
foreach (var tmp in userlist) Response.Write("ID:" + tmp.uid + "
" + "名前:" + tmp.username + "
");
//匿名类型
var tmpuserlist = from u in userlist
where u.uid >= 3
select new { uid=u.uid,username=u.username,intro=u.intro };
foreach (var tmp in tmpuserlist) Response.Write("ID:" + tmp.uid + "
" + "名前:" + tmp.username + "
");

//DataContext连接数据库
DataContext dc = new DataContext(@"F:\wwwroot\LinqTest\Data\LinqTest.mdf");
//GetTable取得数据库中的表
Table tblPost = dc.GetTable();
Table tblComment = dc.GetTable();
//查询综合
var tmpResult = from p in tblPost
from c in tblComment
where p.pid==c.pid
orderby p.pid
select new{pid=p.pid,cid=c.cid,content=p.p_content};
foreach(var item in tmpResult) Response.Write(" CommentID:" + item.cid + " Content:" + item.content + "
");

Back