一、Partitioning 分区
Take
例1:取前3个数
static void Linq1()
{
int[] numbers = { , , , , , , , , , };
var first3Numbers = numbers.Take();
Console.WriteLine("前3个数:");
foreach (var n in first3Numbers)
{
Console.WriteLine(n);
}
}
Skip
例2:跳过前3个数
static void Linq2()
{
int[] numbers = { , , , , , , , , , };
var skip3Numbers = numbers.Skip();
Console.WriteLine("除去前3个数后数字:");
foreach (var n in skip3Numbers)
{
Console.WriteLine(n);
}
}
Take + Skip 实现分页
int currentPageIndex; // 当前页号
int pageSize; // 每页有多少条记录
source 是总数据源集合 则用LINQ分页的代码为 var query = source.Skip((currentPageIndex-) * pageSize).Take(pageSize);
二、Join
例1: Cross Join
static void Linq3()
{
string[] cates = {"酒类","烟类","肉类" };
var products = Product.GetDefaultData(); // CategoryName 没有与 cate 匹配的将被剔除
var query = from c in cates
join p in products on c equals p.CategoryName
select new { ShowName = c + " : " + p.ProductName }; foreach (var item in query)
{
Console.WriteLine(item.ShowName);
}
} public class Product
{
public string CategoryName { get; set; }
public string ProductName { get; set; } public static List<Product> GetDefaultData()
{
return new List<Product>
{
new Product{ CategoryName="烟类", ProductName="中华"},
new Product{ CategoryName="酒类", ProductName="白酒"},
new Product{ CategoryName="酒类", ProductName="红酒"},
new Product{ CategoryName="肉类", ProductName="猪肉"},
new Product{ CategoryName="肉类", ProductName="牛肉"},
new Product{ CategoryName="零食", ProductName="饼干"},
new Product{ ProductName="暂未分类产品1"},
new Product{ ProductName="暂未分类产品2"},
};
}
}
例2: Group Join
static void Linq4()
{
string[] cates = { "酒类", "烟类", "肉类" };
var products = Product.GetDefaultData(); var query = from c in cates
join p in products on c equals p.CategoryName
into tgroup
select new { Name = c, Group = tgroup }; foreach (var item in query)
{
Console.Write("{0}: ",item.Name);
foreach (var g in item.Group)
{
Console.Write("{0} ",g.ProductName);
}
Console.WriteLine();
}
}
例3:Cross Join + Group Join
分组后再查询符合条件的
static void Linq5()
{
string[] cates = { "酒类", "烟类", "肉类" };
var products = Product.GetDefaultData(); var query = from c in cates
join p in products on c equals p.CategoryName
into tgroup
from g in tgroup
where g.ProductName.Contains("牛腩") // 仅要产品名字含有牛腩的分组
select new { Name = c, Group = tgroup }; foreach (var item in query)
{
Console.Write("{0}: ", item.Name);
foreach (var g in item.Group)
{
Console.Write("{0} ", g.ProductName);
}
Console.WriteLine();
}
}
例4 Left Outer Join
static void Linq6()
{
string[] cates = { "酒类", "烟类", "肉类" ,"调料类"};
var products = Product.GetDefaultData(); var query = from c in cates
join p in products on c equals p.CategoryName
into tgroup
from g in tgroup.DefaultIfEmpty()
select new { Name = c, ProductName = g==null ? "该分组下没有内容":g.ProductName }; foreach (var item in query)
{
Console.WriteLine("{0} {1}",item.Name,item.ProductName);
}
}
三、 聚合
Count();
Count(n => 条件); 后面都类似
Sum();
Min()
Max()
Average()
本文代码:http://files.cnblogs.com/Aphasia/ConsoleApplication2.rar