如何合并Class和Generic List<;T>;使用LINQ

本文关键字:lt gt LINQ 使用 List Generic 何合并 合并 Class | 更新日期: 2023-09-27 18:19:41

如何根据以下示例合并class和Generic List这两个对象?

public class BookShop
{
    public Author Author { get; set; }
    public List<Book> Book { get; set; }
}
public class Author
{
    public string ID { get; set; }
    public string Name { get; set; }
}
public class Book
{
    public int ID { get; set; }
    public string Name { get; set; }
}
public class BookDetail
{
    public int ID { get; set; }
    public string Comment { get; set; }
    public int BookID { get; set; }
}
List<BookShop> shop = db.GetBook();
List<BookDetail> bookDetail = db.GetBookDetail();
var merge = shop.Select(m => m.Book.Join(bookDetail, ok => ok.ID, ik => ik.BookID, (b, d) => new
{
    b.ID,
    b.Name,
    d.Comment
}));

到目前为止一切都还可以,但我需要编写详细信息(Author.Name)

如何合并Class和Generic List<;T>;使用LINQ

您似乎在使用实体框架。你的结构应该更像这样:

public class Author
{
    public string ID { get; set; }
    public string Name { get; set; }
    public virtual IEnumerable<Book> Books { get; set; } 
}
public class Book
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int AuthorID { get; set; }
    public Author Author { get; set; }
    public IEnumerable<BookDetail> Details { get; set; }
}
public class BookDetail
{
    public int ID { get; set; }
    public string Comment { get; set; }
    public int BookID { get; set; }
    public Book Book { get; set; }
}

这使您可以在书籍、作者和书籍详细信息之间建立直接联系。然后在林克,你可以做这样的事情来获得一本书的详细信息

Books.Select(x => new 
{
    ID = x.ID,
    Name = x.Name,
    Comments = x.Details.Select(d => d.Comment)
    Author = x.Author
})