List Publishers = new List(); Publisher publish1 = new Publisher(); publish1.Code = "01"; publish1.Name = "北京出版社1"; Publishers.Add(publish1); ... ...
List<Publisher> Publishers = new List<Publisher>(); Publisher publish1 = new Publisher(); publish1.Code = "01"; publish1.Name = "北京出版社1"; Publishers.Add(publish1); Publisher publish2 = new Publisher(); publish2.Code = "02"; publish2.Name = "北京出版社2"; Publishers.Add(publish2); List<Book> Books = new List<Book>(); Book boo1 = new Book(); boo1.Publisher = new Publisher() { Name = "北京出版社1",Code="01" }; boo1.Title = "書名1"; boo1.PublisherCode = "01"; Books.Add(boo1); Book boo2 = new Book(); boo2.Publisher = new Publisher() { Name = "北京出版社2",Code="02" }; boo2.Title = "書名2"; boo2.PublisherCode = "02"; Books.Add(boo2); Book boo3 = new Book(); boo3.Publisher = new Publisher() { Name = "北京出版社2",Code="02" }; boo3.PublisherCode = "02"; boo3.Title = "書名3"; Books.Add(boo3); //使用組連接 var GroupQuery = (from publisher in Publishers join book in Books on publisher equals book.Publisher into publisherBooks select new { PublisherName = publisher.Name, Books = publisherBooks }).ToList(); //使用Group var QueryByGroup = (from book in Books group book by book.Publisher into grouping select new { PublisherName = grouping.Key.Name, Books = grouping.ToList() }).ToList(); var joinQuery = from publisher in Publishers join book in Books on publisher equals book.Publisher select new { PublisherName = publisher.Name, BookName = book.Title }; var tem = joinQuery.ToList(); //left join var joinQuery2 = (from publisher in Publishers join book in Books on publisher.Code equals book.PublisherCode into publisherBooks from publisherBook in publisherBooks.DefaultIfEmpty() select new { PublisherName = publisher.Name, BookName = (publisherBook == default(Book)) ? "no book" : publisherBook.Title }).ToList(); //cross join var crossJoinQuery = (from publisher in Publishers from book in Books select new { PublisherName = publisher.Name, BookName = book.Title }).ToList();