目前,我有一个程序可以对一系列书籍进行排序&作者。现在,它是由按标题分组的作者输出,这意味着它打印作者的姓名&他/她写的所有书。好吧,我正试图扭转那个&按书本输出,&然后是所有撰写该书的作者。很多人会非常感激。
// get authors and titles of each book
// they co-authored; group by author
var titlesByAuthor =
from author in dbcontext.Authors
orderby author.LastName, author.FirstName
select new
{
Name = author.FirstName + " " + author.LastName,
Titles =
from book in author.Titles
orderby book.Title1
select book.Title1
};
outputTextBox.AppendText("\r\n\r\nTitles grouped by author:");
// display titles written by each author, grouped by author
foreach (var author in titlesByAuthor)
{
//display author's name
outputTextBox.AppendText("\r\n\t" + author.Name + ":");
// display titles written by that author
foreach (var title in author.Titles)
{
outputTextBox.AppendText("\r\n\t\t" + title);
}
}
答案 0 :(得分:0)
请使用linq group by operator按书籍分组。这是一个示例:
public void Linq40()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var numberGroups =
from n in numbers
group n by n % 5 into g
select new { Remainder = g.Key, Numbers = g };
foreach (var g in numberGroups)
{
Console.WriteLine("Numbers with a remainder of {0} when divided by 5:", g.Remainder);
foreach (var n in g.Numbers)
{
Console.WriteLine(n);
}
}
}
答案 1 :(得分:0)
以下查询将为您提供所需内容:
var booksByAuthor =
from book in dbcontext.Books
orderby book.Title1
select new
{
Authors =
from a in book.Authors
orderby a.LastName, a.FirstName
select a.FirstName + " " + a.LastName
Titles = book.Title1
};
你应该能够自己弄清楚其他部分。
<强>更新强>
foreach (var book in booksByAuthor)
{
//display book's title
outputTextBox.AppendText("\r\n\t" + book.Title1 + ":");
// display authors of that book
foreach (var author in book.Authors)
{
outputTextBox.AppendText("\r\n\t\t" + author);
}
}