代码改变世界

C#3.0新特性示例学习(七)-Linq to object(4)分组查询

2011-04-04 19:08  杨延成  阅读(408)  评论(0编辑  收藏  举报
 1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5
6namespace TestLinQ2
7{
8 public class Book
9{
10 public string Title { set; get; }
11 public Author Book_Author { set;get;}
12 public float Price { set; get; }
13 }
14 public class Author
15{
16 public string Name { set; get; }
17 public string Address { set;get;}
18 }
19
20 public class TestLinq3
21 {
22 public void TestMethod()
23{
24 List<Book> bookList = new List<Book>
25{
26 new Book[color=]...{Title="C#高级编程",Book_Author=new Author{Name="黄老邪",Address="桃花岛"},Price=128f},
27 new Book[color=]...{Title="Think in Java",Book_Author=new Author{Name="欧阳峰",Address="白驼山"},Price=128f},
28 new Book[color=]...{Title="silverlight",Book_Author=new Author{Name="一灯大师",Address="大理"},Price=128f},
29 new Book[color=]...{Title="JavaFx",Book_Author=new Author{Name="洪七公",Address="临安"},Price=125f}
30
31 };
32
33
34///查询所有黄老邪写的书
35 //var mybook = bookList
36 // .Where(book => book.Book_Author.Name.Equals("黄老邪"))
37///注意下面这种写法,象不象是匿名类
38 // .Select(book => new { Title=book.Title,MyAuthor=book.Book_Author.Name,My_Price=book.Price });
39
40 //foreach (var item in mybook)
41 //{
42 // Console.Write(string.Format("书名{0} 价格{1} 作者{2}",item.Title , item.My_Price.ToString() , item.MyAuthor));
43
44 //}
45
46
47///分组查询 按价格分组
48 var mybook = bookList
49 .GroupBy(book => book.Price);
50
51
52
53 foreach (var item in mybook)
54{
55///显示每组的数据,聚合数据
56 Console.WriteLine(string.Format("分组依据:{0} 每组最大的书名{1} 每组数量{2}", item.Key,item.Max(book=>book.Title),item.Count()));
57
58 foreach (var newbook in item)
59{
60///这个可以遍历每个组里的数据了
61 Console.WriteLine(newbook.Title);
62 }
63 }
64
65 }
66 }
67}