问题描述:
对于下面的定义和初始化数据
public class Author
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class Book
{
public string Name { get; set; }
public List<Author> Authors { get; set; }
}
var authors = new List<Author>()
{
new Author() { FirstName = "Fabric", LastName = "Marguarie" },
new Author() { FirstName = "Steve", LastName = "Eichert" },
new Author() { FirstName = "Jim", LastName = "Wooley" },
new Author() { FirstName = "Jon", LastName = "Skeet" },
new Author() { FirstName = "Tom", LastName = "Steve" }
};
var books = new List<Book>()
{
new Book() { Name = "LINQ in action", Authors = new List<Author>()
{
authors[0], authors[1], authors[2]
}},
new Book() { Name = "C# in depth", Authors = new List<Author>()
{
authors[3]
}},
new Book() { Name = "LINQ internal", Authors = new List<Author>()
{
authors[0], authors[4]
}},
};
要求查询出图书标题包含“LINQ”关键字的作者,且每个作者最多只能出现一次。
实现:
var results = from distinceAuthor in
(from book in books
where book.Name.Contains("LINQ")
from author in book.Authors
select author)
.Distinct()
select new { distinceAuthor.FirstName, distinceAuthor.LastName };
var results2 = books
.Where(book => book.Name.Contains("LINQ"))
.SelectMany(book => book.Authors)
.Distinct()
.Select(author => new { author.FirstName, author.LastName });
foreach (var result in results)
{
Console.WriteLine("{0} {1}", result.FirstName, result.LastName);
}