Reputation: 15
Have some problem. Need to sort the list by another collection:
List<Books> b = new List<Books>();
Class 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; }
}
Class 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; }
}
Class Authors:
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; }
}
How i can sort b by authors last name?
Upvotes: 0
Views: 76
Reputation: 155692
Something like this, though with mutiple authors it remains a question which author you order by:
var sorted =
from book in b
let firstAuthor = book.BookAuthors.First()
let lastName = firstAuthor.LastName
order book by lastName
select book
Alternatively you could apply some logic (if you had it)...
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
Upvotes: 4