c# - 遍历列表并动态创建摘要行

标签 c# loops

编辑:我错过了一个关键点:.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/

相关文章:

php - 循环遍历一个查询的结果并将其插入到另一个查询中,并联合第二个查询的所有结果

C#;列表框作为一个对象(容器)

Python 冒险游戏 -> 在 while 循环中选择 A 或 B 不起作用!

c# - 在调用 BuildServiceProvider 之前将 dotnet 核心依赖注入(inject)到扩展方法

c# - 允许用户访问[授权]页面 - MVC

Java "break"似乎打破了两个嵌套的 for 循环

php - 循环遍历 XML,仅在特定 ID 处循环 "look"

java - 如何在for循环中添加连字符

c# - 比较相同用户定义类型的两个列表

c# - 如何使用 C# 从 mpg 视频创建缩略图?