您的位置:首页 > 其它

Linq的常用查询和操作总结实例

2013-03-11 21:56 831 查看
简单的LINQ查询

static void Main(string[] args)

{

int[] marks = { 60, 77, 82, 46, 59, 98, 100, 84 };//定义一个数组

var good = from m in marks//使用LINQ找到所有数值大于等于60的数字

where m >= 60

select m;

foreach (int mark in good)//循环每一个结果

{

Console.WriteLine(mark);//输出结果

}

}

使用Lambda表达式的LINQ查询

static void Main(string[] args)

{

int[] marks = { 60, 77, 82, 46, 59, 98, 100, 84 };

var good = marks.Where(m => m >= 60);//使用Lambda表达式查询数值大于等于60的数字

foreach (int mark in good)//循环每一个结果

{

Console.WriteLine(mark);//输出结果

}

}

使用LINQ查询对象集合

class Program

{

static void Main(string[] args)

{

List<Student> students = new List<Student>//申明Student对象的集合

{

new Student{ StudentID=1, Sex=true, Name="何欢", Birthday=Convert.ToDateTime("1984-1-1")},

new Student{ StudentID=2, Sex=false, Name="晏婉", Birthday=Convert.ToDateTime("1983-5-1")},

new Student{ StudentID=3, Sex=true, Name="高伟", Birthday=Convert.ToDateTime("1983-2-15")},

new Student{ StudentID=4, Sex=false, Name="叮叮", Birthday=Convert.ToDateTime("1985-3-8")}

};

//接下来使用LINQ查询所有年龄小于25岁的男性

var names = from s in students

where s.Sex == true&&s.GetAge()<25 //调用对象的方法

select s.Name;

foreach (string name in names)//循环输出结果

{

Console.WriteLine(name);

}

}

}

public class Student //定义Student类

{

//以下是定义类中属性

public string Name { get; set; }

public int StudentID { get; set; }

public bool Sex { get; set; }

public DateTime Birthday { get; set; }

//以下是定义类中的方法

public int GetAge()

{

return DateTime.Now.Year - Birthday.Year;

}

}

--

--11.8.2节示例

--

--创建示例数据库

CREATE TABLE Class --创建班级表

(

ClassID INT PRIMARY KEY,

ClassName NVARCHAR(20) NOT NULL

)

GO

CREATE TABLE Student --创建学生表

(

StudentID INT IDENTITY PRIMARY KEY,

NAME NVARCHAR(10) NOT NULL,

Sex BIT NOT NULL,

BirthDay DATETIME NOT NULL,

ClassID INT NOT NULL,

--以下定义的是外键约束

CONSTRAINT FK_Student_Class FOREIGN KEY(ClassID) REFERENCES Class(ClassID)

)

GO

--以下是插入示例数据

INSERT INTO Class VALUES(1,'200801');

INSERT INTO Class VALUES(2,'200802');

INSERT INTO Student ([NAME],Sex,BirthDay,ClassID) VALUES ('张三',1,'1982-1-12',1)

INSERT INTO Student ([NAME],Sex,BirthDay,ClassID) VALUES ('李四',1,'1983-11-2',1)

INSERT INTO Student ([NAME],Sex,BirthDay,ClassID) VALUES ('何欢',1,'1982-8-6',2)

INSERT INTO Student ([NAME],Sex,BirthDay,ClassID) VALUES ('晏婉',0,'1983-6-15',2)

通过StuDataClassesDataContext查询学生

static void Main(string[] args)

{

StuDataClassesDataContext context=new StuDataClassesDataContext();//申明对象

var students=from s in context.Student //LINQ查询所有学生的名字

select s.NAME;

foreach(var name in students) //循环输出所有学生的姓名

{

Console.WriteLine(name);

}

}

--

--11.8.3节示例

--

使用LINQ的多表联接查询

static void Main(string[] args)

{

StuDataClassesDataContext context=new StuDataClassesDataContext();

var students = from s in context.Student

from c in context.Class

where s.ClassID == c.ClassID //相当于连接两个表

select new //返回了学生的名字和班级的名字

{

s.NAME,

c.ClassName

};

foreach(var o in students) //循环输出所有学生的名字和对应班级的名字

{

Console.WriteLine(o.NAME+" "+o.ClassName);

}

}

使用LINQ进行外联结查询

var students = from s in context.Student

join c in context.Class

on s.ClassID equals c.ClassID into cla

from cl in cla.DefaultIfEmpty() //这里相当于一个外联结操作

select new

{

s.NAME,

cl.ClassName

};

使用LINQ进行嵌套查询

var students = from c in context.Class

join s in context.Student

on c.ClassID equals s.ClassID into st //嵌套查询

select new //输出班级的名字和班级中的学生数

{

c.ClassName,

StudentCount=st.Count()

};

--

--11.8.4节示例

--

在LINQ中使用分组查询

var students = from s in context.Student

group s by s.Sex into sex //使用Sex属性进行分组

select new//输出性别和性别对应的人数

{

Sex = sex.Key,

Count = sex.Count()

};

使用LINQ进行排序

var students = from s in context.Student

orderby s.NAME descending //使用Name进行反序排列

select s.NAME;

使用LINQ进行Union操作

var students = (from s in context.Student

select s.NAME).Concat //联合下一个查询

(from c in context.Class

select c.ClassName);

使用LINQ进行分页查询

var students = (from s in context.Student

orderby s.NAME

select s.NAME).Skip(2).Take(2); //分页操作

使用SqlMethods类进行LINQ的LIKE查询

var students = from s in context.Student

where SqlMethods.Like(s.NAME,"张%") //对Name进行Like查询

select s.NAME;

--

--11.8.5节示例

--

使用LINQ to SQL修改数据

StuDataClassesDataContext db=new StuDataClassesDataContext();

Student student = db.Student.First(s => s.StudentID == 1); //找到学生ID为1的学生对象

student.NAME = "张润"; //修改该学生对象的姓名

db.SubmitChanges(); //提交修改

使用LINQ to SQL删除数据

StuDataClassesDataContext db = new StuDataClassesDataContext();

var cla = from c in db.Class //找到班级ID为3的班级对象

where c.ClassID == 3

select c;

db.Class.DeleteOnSubmit(cla); //删除该班级对象

db.SubmitChanges(); //提交删除操作

--

--11.8.6节示例

--

创建存储过程

CREATE PROC GetStudentByID --创建一个简单的存储过程

@id INT --参数

AS

SELECT * --简单的SQL查询

FROM Student

WHERE StudentID=@id

在LINQ to SQL中调用存储过程

StuDataClassesDataContext db = new StuDataClassesDataContext();

var student = db.GetStudentByID(1); 调用//存储过程对应的方法

foreach (var s in student)

{

Console.WriteLine(s.NAME); //输出存储过程返回的结果中的Name列

}

在LINQ to SQL中执行SQL语句查询

StuDataClassesDataContext db = new StuDataClassesDataContext();

var cla = db.ExecuteQuery<Class>("select * from Class"); //定义SQL查询语句并执行

foreach (var c in cla) //循环输出查询返回的每一个结果

{

Console.WriteLine(c.ClassID+" "+c.ClassName);

}

在LINQ to SQL中执行SQL语句

StuDataClassesDataContext db = new StuDataClassesDataContext();

//以下代码执行数据库修改,并返回受影响的行数

int count=db.ExecuteCommand("update Student set Birthday='1983-12-11' where StudentID=4");

Console.WriteLine(count);//输出结果:1

在LINQ to SQL中使用事务

StuDataClassesDataContext db = new StuDataClassesDataContext();

SqlConnection conn = (SqlConnection)db.Connection;//获得连接

conn.Open();//打开连接

SqlTransaction trans = (SqlTransaction)db.Connection.BeginTransaction();//创建事务

db.Transaction = trans;//将事务赋予LINQ to SQL实例

try

{

db.Student.DeleteAllOnSubmit(from s in db.Student //删除班级ID为1的所有学生

where s.ClassID == 1

select s);

db.Class.DeleteAllOnSubmit(from c in db.Class //删除班级ID为1的所有班级

where c.ClassID == 1

select c);

db.SubmitChanges(); //提交更改

trans.Commit(); //提交事务

}

catch //发生异常时回滚事务

{

trans.Rollback();

}

finally //关闭连接

{

conn.Close();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: