namespace LinqApplication
{
public partial class MainPage : PhoneApplicationPage
{
List Books;//List继承了IEnumerable 接口
public MainPage()
{
InitializeComponent();
CreateBooks();
//IEnumerable.Select 将序列中的Authors元素投影到新表中。
IEnumerable EnumerableOfListOfAuthors = Books.Select(book => book.Authors);
foreach (var listOfAuthors in EnumerableOfListOfAuthors)
{
foreach (Author auth in listOfAuthors)
{
Output.Items.Add(auth.Name); //添加到ListBox里面
}
}
//IEnumerable.SelectMany 将序列的每个元素投影到 IEnumerable 并将结果序列合并为一个序列。
IEnumerable authors = Books.SelectMany(book => book.Authors);
foreach (Author auth in authors)
{
Output2.Items.Add(auth.Name);
}
}
private void CreateBooks()
{
Books = new List();
Author auth1 = new Author() { Name = "张三", Age = 32 };
Author auth2 = new Author() { Name = "李四", Age = 30 };
Author auth3 = new Author() { Name = "加菲猫", Age = 31 };
List authors = new List() { auth1, auth2, auth3 };
Book newBook = new Book() { Authors = authors, NumPages = 500, Title = "Programming C#" };
Books.Add(newBook); auth1 = new Author() { Name = "刘德华", Age = 42 };
authors = new List() { auth1 };
newBook = new Book() { Authors = authors, NumPages = 350, Title = "Book 2" };
Books.Add(newBook); auth1 = new Author() { Name = "周杰伦", Age = 32 };
auth2 = new Author() { Name = "林志玲", Age = 32 };
authors = new List() { auth1, auth2 };
newBook = new Book() { Authors = authors, NumPages = 375, Title = "Programming with WP7" };
Books.Add(newBook);
}
}
}
Author.cs类
namespace LinqApplication
{
public class Author
{
public string Name;
public int Age;
}
}
Book.cs类
namespace LinqApplication
{
public class Book
{
public String Title { get; set; }
public List Authors { get; set; }
public int NumPages { get; set; }
}
}