一、概述
语言集成查询(Language Integrated Query),查询操作数据的工具。
二、使用方式
1、投射
投射是一种查询操作,从数据源中选择、变换或映射出出新的集合。Select来进行投射。投射一般会创建一个新的集合,而不会修改原数据。3
例:对订单列表进行投射,并且对价格打八折
using System.Net;
using System.Threading.Tasks;
using System.Linq;
class Program
{
static readonly object _sync = new object();
struct Order
{
public int id;
public string name;
public float price;
};
static void Main()
{
List<Order> orders = new List<Order>(){
new Order(){id =1,name = "Order1",price=100},
new Order(){id =2,name = "Order2",price=200},
new Order(){id =3,name = "Order3",price=300}
};
var sale = orders.Select((order) => new { id = order.id, name = order.name, price = order.price * 0.8f });
foreach (var item in sale)
{
Console.WriteLine(string.Format("{0},{1},{2}", item.id, item.name, item.price));
}
}
}
2、查询
例:查询订单号为2的订单
using System.Net;
using System.Threading.Tasks;
using System.Linq;
class Program
{
static readonly object _sync = new object();
struct Order
{
public int id;
public string name;
public float price;
};
static void Main()
{
List<Order> orders = new List<Order>(){
new Order(){id =1,name = "Order1",price=100},
new Order(){id =2,name = "Order2",price=200},
new Order(){id =3,name = "Order3",price=300}
};
var sale = orders.Where((order) => order.id == 2);
foreach (var item in sale)
{
Console.WriteLine(string.Format("{0},{1},{2}", item.id, item.name, item.price));
}
}
}
3、排序
OrderBy
和 OrderByDescending
,分别是顺序和逆序。ThenBy
和 ThenByDescending
可以进行级排序。
例:按照订单顺序进行正向排序。
using System.Net;
using System.Threading.Tasks;
using System.Linq;
class Program
{
static readonly object _sync = new object();
struct Order
{
public int id;
public string name;
public float price;
};
static void Main()
{
List<Order> orders = new List<Order>(){
new Order(){id =1,name = "Order1",price=100},
new Order(){id =3,name = "Order3",price=300},
new Order(){id =2,name = "Order2",price=200}
};
var sale = orders.OrderBy((order) => order.id);
foreach (var item in sale)
{
Console.WriteLine(string.Format("{0},{1},{2}", item.id, item.name, item.price));
}
}
}
4、分组
对数据根据类型进行分组
例:根据订单类型进行排序
using System.Net;
using System.Threading.Tasks;
using System.Linq;
class Program
{
static readonly object _sync = new object();
struct Order
{
public int id;
public string name;
public float price;
public int orderType;
};
static void Main()
{
List<Order> orders = new List<Order>(){
new Order(){id =1,name = "Order1",price=100,orderType = 1},
new Order(){id =3,name = "Order3",price=300,orderType = 1},
new Order(){id =2,name = "Order2",price=200,orderType = 2}
};
var orderGroups = from order in orders group order by order.orderType;
foreach (var group in orderGroups)
{
foreach (var order in group)
{
Console.WriteLine("{0},{1},{2}", order.id, order.name, order.price);
}
Console.WriteLine("--------");
}
}
}
留言