static void Main(string[] args)
{
var products=new[]
{
new{ProductName="Apple",Category="Food"},
new{ProductName="Cat",Category="Animal"},
new{ProductName="Dog",Category="Other"},
new{ProductName="Pig",Category="Animal"},
};
var q = from p in products
group p by p.Category into g
orderby g.Key
select g;
foreach (var item in q)
{
Console.WriteLine(item.Key);
foreach (var i in item)
{
Console.WriteLine("\t" + i.ProductName);
}
}
Console.Read();
}
另外一个结合join的例子
static void Main(string[] args)
{
NorthwindDataContext db = new NorthwindDataContext();
var products = db.Products;
var categorys = db.Categories;
var query = from result in
from p in products.AsEnumerable()
join c in categorys.AsEnumerable()
on p.CategoryID equals c.CategoryID //这里必须写equals,而不能是=
select new { CategoryName = c.CategoryName, Product = p }
group result by result.CategoryName into g
select g;
foreach (var group in query)
{
Console.WriteLine(group.Key);
foreach (var product in group)
{
Console.WriteLine("\t"+product.Product.ProductName);
}
}
Console.Read();
}
【注意】我这里用的是LINQ TO SQL模型,访问了Northwind这个数据库