我的预期输出是:
扩展名:.txt-CATS.TXT-DOGS.TXT扩展名:.pdf- INFO.PDF-TEST2.PDF扩展名:.doc-Summary.DOC- TEST1.DOC
这里是功能。
public void TestGroupByFluentSyntax()
{
string[] files = new string[] { "test1.doc", "test2.pdf", "cats.txt", "dogs.txt", "info.pdf", "summary.doc" };
IEnumerable<IGrouping<string, string>> query = files.GroupBy(file => System.IO.Path.GetExtension(file), file => file.ToUpper())
.OrderBy(grouping => grouping.Key);
foreach(IGrouping<string, string> grouping in query)
{
Console.WriteLine("Extension: " + grouping.Key);
foreach (string fileName in grouping)
Console.WriteLine(" -- " + fileName);
}
}
public void TestGroupByFluentSyntax2()
{
string[] files = new string[] { "test1.doc", "test2.pdf", "cats.txt", "dogs.txt", "info.pdf", "summary.doc" };
IEnumerable<IGrouping<string, string>> query = files.OrderBy(file => file).GroupBy(file => System.IO.Path.GetExtension(file), file => file.ToUpper());
foreach (IGrouping<string, string> grouping in query)
{
Console.WriteLine("Extension: " + grouping.Key);
foreach (string fileName in grouping)
Console.WriteLine(" -- " + fileName);
}
}
如果我先订购,然后将其分组。但是分组和排序却没有。我在分组并排序后的功能 TestGroupByFluentSyntax ()'上缺少什么?
答案 0 :(得分:0)
您并不遥远。在TestGroupByFluentSyntax()
中,您的输出为:
Extension: .doc
-- TEST1.DOC
-- SUMMARY.DOC
Extension: .pdf
-- TEST2.PDF
-- INFO.PDF
Extension: .txt
-- CATS.TXT
-- DOGS.TXT
您按扩展名分组并按扩展名排序。因此,显示时,扩展名来自doc,pdf和txt。但是每个组中的文件未排序。您可以实现所需的输出(通过反转扩展顺序-将OrderByDescending
用作:
IEnumerable<IGrouping<string, string>> query
= files.GroupBy(file => System.IO.Path.GetExtension(file), file => file.ToUpper())
.OrderByDescending(grouping => grouping.Key);
然后,当您显示(对每个组进行排序-使用OrderBy
)时,请使用:
foreach (string fileName in grouping.OrderBy(name => name))
Console.WriteLine(" -- " + fileName);
这将是输出:
Extension: .txt
-- CATS.TXT
-- DOGS.TXT
Extension: .pdf
-- INFO.PDF
-- TEST2.PDF
Extension: .doc
-- SUMMARY.DOC
-- TEST1.DOC
答案 1 :(得分:0)
This worked:
public void TestGroupByFluentSyntax()
{
Console.WriteLine("TestGroupByFluentSyntax");
string[] files = new string[] { "test1.doc", "test2.pdf", "cats.txt", "dogs.txt", "info.pdf", "summary.doc" };
IEnumerable<IGrouping<string, string>> query = files.GroupBy(file => System.IO.Path.GetExtension(file), file => file.ToUpper());
foreach (IGrouping<string, string> grouping in query)
{
Console.WriteLine("Extension: " + grouping.Key);
foreach (string fileName in grouping.OrderBy(name => name))
Console.WriteLine(" -- " + fileName);
}
}