语言集成查询(LINQ)

来源:互联网 发布:基金知乎 编辑:程序博客网 时间:2024/04/30 07:36

简介

LINQ是 Visual Studio 2008 和 .NET Framework 3.5 版中引入的一项创新功能,它在对象领域和数据领域之间架起了一座桥梁,
可能读者会说,linq在大并发大数据量是会很慢,单我们不能凭此一点就抹杀了linq,linq在很多方面还是很有用的,比如:
当我们需要从数据集中查询某个或者某些符合条件的对象时,用linq也就是一句话的事,若你用foreach,再用各种if判断,最终
取得符合条件的对象时,是不是显得代码太臃肿了,不仅仅这种场合,linq提供的对各种数据源统一的操作方式,大大减少了编程人员的学习难度,

完整语法

首先需要说明的是,linq分为linq表达式和linq方法两种使用方式,本文侧重于linq表达式
 //定义数据源
 var objs = [***];//这里用数组做数据源
 //定义查询变量
 IEnumerable<T>  queryResult = 
from obj in objs
let temps = obj***//可以对obj对象对一些比如拆分等等的操作
from temp in temps
join *** on **** == *** //连接
//let tem = temp***
where *** == *** && //且
 *** == *** || //或
 *** == ***
group *** by *** into ***
order by ***
select ***;//此处可以返回对象或者对象的属相,甚至可以自定义匿名对象,通过new {key = value,key = value}形式
//查询
foreach(var queryObj in queryResult){
//操作
}

几点说明

1.linq使用都要有类似上述的3个步骤,定义数据源,定义查询变量,开始查询 //定义查询变量并没有真正的开始查询,当从查询变量去数据时,才开始真正的查询,查询变量并不存储任何值,
2.***代表进一步操作
3.上文中的T,obj,temp select后的对象,类型一定要一致
4.objs集合一定要是实现IEnumerable接口或者实现IQueryable
5.上面的linq关键词常用的也就from,where,orderby,select几个
6.得到queryResult,就可以利用IEnumerable<T>提供的方法进一步操作,Distinct,tolist,count等等
7.凡是实现了IEnumerable<T>接口的集合类,可以直接利用提供的select,where等等方法来查询,过滤,分组,和linq表达式查询一样的,只是做了封装
8.查询的结果集还可以通过,union,concat(union all),Intersect,Except实现联合查询

分类和使用

linq按照使用场景,也就是操作的数据源类型,可以分为这么几类:

1.linq to objects

例子:
//定义数据源
ArrayList arrList = new ArrayList();
            arrList.Add(
                new Student
                    {
                        FirstName = "Svetlana", LastName = "Omelchenko", Scores = new int[] { 98, 92, 81, 60 }
                    });
            arrList.Add(
                new Student
                    {
                        FirstName = "Claire", LastName = "O’Donnell", Scores = new int[] { 75, 84, 91, 39 }
                    });
//定义查询变量
            var query = from Student student in arrList
                        where student.Scores[0] > 95
                        select student;
//查询
            foreach (Student s in query){
                Console.WriteLine(s.LastName);
}

2.linq to xml

例子:
//数据源
XElement root = XElement.Load("PurchaseOrder.xml");
//查询变量
IEnumerable<XElement> address =
from el in root.Elements("Address")
where (string)el.Attribute("Type") == "Billing"
select el;
//查询
foreach (XElement el in address)
Console.WriteLine(el);


3.linq to ado.net

1)linq to dataset

例子:
//数据源,一般使用是数据库中的查询结果,填充到dataset中,然后products = ds.Tables["Name"];
//这里为了代码可执行,自己填充了datatable
DataTable products = new DataTable();
products.Columns.Add("ID");
products.Columns.Add("Size");
for(int i=1;i<=10;i++)
{
if(i<5){
products.Rows.Add(new object[]{i,"L"});
}else{
products.Rows.Add(new object[]{i,"H"});
}
}
//查询变量
            IEnumerable<DataRow> productsQuery =
                from product in products.AsEnumerable()
                select product;//linq表达式查询


            IEnumerable<DataRow> largeProducts =
                productsQuery.Where(p => p.Field<string>("Size") == "L");//linq方法查询
//查询
            foreach (DataRow product in largeProducts)
            {
                Console.WriteLine(product.Field<string>("ID"));
            }


2)linq to sql

例子:
首先在项目中建立linq to sql类
再者用服务器资源管理器连接数据库,把相应的表拖到对象关系设计器上
设计好后,会生成这么几个对象dataContext(数据上下文对象,linq to sql操作的入口),Customers(实体集合,对应数据库中的表),实体(对应数据库中的表里的一行)
//查询变量
var queryResult = from c in dataContext.Customers
 where c.Country == "France" && c.Orders.Count > 5
 select new
 {
 国家 = c.Country,
 城市 = c.City,
 订单数 = c.Orders.Count
 };
//把查询结果绑定到控件即可
//顺便说说linq to sql的其他操作
add(增加)
Customer customer = new Customer
{
//属性赋值
};
Console.WriteLine("----------begin Add a Customer");
using (DataClasses1DataContext dataContext = new DataClasses1DataContext())
{
dataContext.Students.InsertOnSubmit(customer);
dataContext.SubmitChanges();
}
edit(编辑)
//取出customer
int id = 1111;//应该是传参得到的
var customer = dataContext.Customers.SingleOrDefault<Customer>(s=>s.ID == id);
//修改customer的属性
customer.Country = "中国";
customer.City = "张家口"; 
//执行更新操作
dataContext.SubmitChanges();
delete(删除)
//取出customer
int id = 1111;//应该是传参得到的
var customer = dataContext.Customers.SingleOrDefault<Customer>(s=>s.ID == id);
//修改customer的属性
dataContext.Customers.DeleteOnSubmit(customer); 
//执行更新操作
dataContext.SubmitChanges(); 

3)linq to entities

例子:
此是使用场景主要针对entity framework,如果对ef不是了解,请先学习ef的最基本知识
using (AdventureWorksEntities context = new AdventureWorksEntities())//ef中的上下文
{
//返回的类型是IQueryable派生类,而不是IEnumerable派生类
IQueryable<int> salesInfo =
from s in context.SalesOrderHeaders//ef中的集合
where s.TotalDue >= totalDue
select s.SalesOrderID;


Console.WriteLine("Sales order info:");
foreach (int orderNumber in salesInfo)//查询
{
Console.WriteLine("Order number: " + orderNumber);                    
}
}
ps:
如果你想对linq更深入的学习,下面是ms的中文官方网址
http://msdn.microsoft.com/zh-cn/library/bb397926.aspx

0 0
原创粉丝点击