按其他集合列出排序

本文关键字:排序 集合 其他 | 更新日期: 2023-09-27 18:31:37

有一些问题。需要按另一个集合对列表进行排序:

List<Books> b = new List<Books>();

课本:

public partial class Books
{
    public Books()
    {
        this.BookAuthors = new HashSet<BookAuthors>();
    }
    public int BookID { get; set; }
    public string BookName { get; set; }
    public virtual ICollection<BookAuthors> BookAuthors { get; set; }
}

班级书籍作者:

public partial class BookAuthors
{
    public int Id { get; set; }
    public int AuthorID { get; set; }
    public int BookID { get; set; }
    public virtual Books Books { get; set; }
    public virtual Authors Authors { get; set; }
}

班级作者:

public partial class Authors
{
    public Authors()
    {
        this.BookAuthors = new HashSet<BookAuthors>();
    }
    public int AuthorID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public virtual ICollection<BookAuthors> BookAuthors { get; set; }
}

我如何按作者姓氏对 b 进行排序?

按其他集合列出排序

像这样的东西,尽管对于多个作者来说,您按哪个作者订购仍然是一个问题:

var sorted = 
    from book in b
    let firstAuthor = book.BookAuthors.First()
    let lastName = firstAuthor.LastName
    order book by lastName 
    select book

或者,您可以应用一些逻辑(如果有的话)...

var sorted = 
    from book in b
    let author = book.BookAuthors.FirstOrDefault(a=>a.Primary) ?? 
        book.BookAuthors.FirstOrDefault(a=>a.Editor) ??
        book.BookAuthors.First()
    let lastName = author.LastName
    order book by lastName 
    select book