【问题标题】:How can i merge two object both Class and Generic List<T> use LINQ如何合并两个对象,Class 和 Generic List<T> 使用 LINQ
【发布时间】:2015-10-28 22:27:13
【问题描述】:

我怎样才能根据下面的例子合并两个对象类和通用列表?

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)

【问题讨论】:

  • 为什么Author 不是Book 的属性?
  • 我建议重新组织班级结构
  • @YuvalItzchakov,我想将作者实体声明为分开。你是不是走错路了?
  • @GoranZooferic 当我想到一个书籍实体时,这本书的作者绝对应该是其中的一部分。您还看到,现在您实际上需要它作为结果对象的一部分。
  • 我认为您需要一个多对多表来组织它。请记住,一本书可以由许多作者写,一个作者也可以写很多书。

标签: c# linq


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-09
    • 1970-01-01
    相关资源
    最近更新 更多