2014-11-24 61 views
0

有一些問題。 需要使用其它的收集對列表進行排序:OrderBy由另一個集合列表

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

類BookAuthors:

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由作者姓氏?

+0

你現在在做什麼? – blfuentes 2014-11-24 10:21:59

+0

你需要給它一個去吧,我很害怕:) – 2014-11-24 10:22:35

+0

你想排序什麼樣的集合? – 2014-11-24 10:23:08

回答

4

這樣的事情,但如果是包含多個作者仍然您訂購該作者通過一個問題:

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