编辑:我错过了一个关键点:.NET 2.0
考虑我有一个未排序项目列表的情况,为了简单起见,这样的类型:
class TestClass
{
DateTime SomeTime;
decimal SomePrice;
// constructor
}
我需要创建一个类似报告的输出,其中累计了每天的总价格。每一项应占一行,后跟适当的摘要行。
拿这个测试数据:
List<TestClass> testList = new List<TestClass> {
new TestClass(new DateTime(2008,01,01), 12),
new TestClass(new DateTime(2007,01,01), 20),
new TestClass(new DateTime(2008,01,01), 18)
};
期望的输出应该是这样的:
2007-01-01:
20
Total: 20
2008-01-01:
12
18
Total: 30
处理此类情况的最佳方法是什么?对于这样的列表,我会为 TestClass 实现 IComparable 接口(interface),以便可以对列表进行排序。
要创建报告本身,可以使用类似这样的东西(假设我们有方法来完成诸如累积价格、跟踪当前日期等任务):
for (int i=0;i<testList.Count;i++)
{
if (IsNewDate(testList[i]))
{
CreateSummaryLine();
ResetValuesForNewDate();
}
AddValues(testList[i]);
}
// a final summary line is needed to include the data for the last couple of items.
CreateSummaryLine();
这工作正常,但就第二个“CreateSummaryLines”而言,我有一种奇怪的感觉。
您如何处理这种情况(特别是考虑到我们需要使用项目列表<>而不是预先分类的字典或类似的东西这一事实)?
最佳答案
好的,如果您不能使用 LINQ:
(我使用 var 来节省空间,但如有必要,它很容易转换为 C# 2.0...)
var grouped = new SortedDictionary<DateTime, List<TestClass>>();
foreach (TestClass entry in testList) {
DateTime date = entry.SomeTime.Date;
if (!grouped.ContainsKey(date)) {
grouped[date] = new List<TestClass>();
}
grouped[date].Add(entry);
}
foreach (KeyValuePair<DateTime, List<TestClass>> pair in testList) {
Console.WriteLine("{0}: ", pair.Key);
Console.WriteLine(BuildSummaryLine(pair.Value));
}
关于c# - 遍历列表并动态创建摘要行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/211958/