嵌套集合

问题描述:

对于下面的定义和初始化数据

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); 
                }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值