【问题标题】:c# compare different unsorted arraysc# 比较不同的未排序数组
【发布时间】:2016-07-11 20:31:58
【问题描述】:

我还是 C# 的初学者,我还没有找到解决我问题的解决方案。

我几个月前就做了这个,直到现在它运行良好,但我可以预见到将来当团队变大时会出现一些问题。 我有一个包含各种内容的日志文件,但我只对所有学生的“开始”和“停止”时间感兴趣。每周我都会运行这段代码来检查每个人是否在正确的时间开始和停止。并非所有学生每天都来:有些学生每周只有 3 个开始和 3 个停止条目,有些则有 4 或 5 个。 我为每个学生制作了带有参考值的数组(例如 Student1StartTimes)。

现在代码会扫描日志文件两次以查找特定学生的条目。一次是他们的开始时间,一次是他们的停止时间。这些被放置在一个临时数组中,并与它们的参考值进行比较。它们不必完全匹配,几分钟就可以了。 特定学生的输入顺序很重要,因为他们的开始/停止时间可能取决于他们输入的日期。

一个例子如下所示。如前所述,它似乎对我的目的有用,但随着学生数量的增加,for 循环的数量也会增加,我觉得这样做可以更有效。

List<LogEntry> TempList = new List<LogEntry>();

foreach (LogEntry log in LogFile)
{
    if (log.Student == "student1" && log.Type.ToString().Equals("Start"))
    {
        TempList.Add(log);
    }
}
for (int i = 0; i < TempList.Count; i++) 
{
    Console.WriteLine("The difference in time is " + TimeDifference(TempList[i].StartTime, Student1StartTimes[i]) + " minutes." );         
}
TempList.Clear(); //Clear the temporary list

foreach (LogEntry log in LogFile)
{
    if (log.Student == "student2" && log.Type.ToString().Equals("Start"))
    {
        TempList.Add(log);
    }
}
for (int i = 0; i < TempList.Count; i++) 
{
    Console.WriteLine("The difference in time is " + TimeDifference(TempList[i].StartTime, Student2StartTimes[i]) + " minutes." );     
}
TempList.Clear(); //Clear the temporary list

【问题讨论】:

  • 我投票结束这个问题作为题外话,因为代码已经工作;没有问题需要解决。
  • 并查看并行扩展,如果分配允许,还可以使用 HashSet。

标签: c# arrays list compare


【解决方案1】:

您是否将学生存储在集合中?

如果是这样循环遍历每个学生,那么您可以在学生循环中循环遍历日志:

foreach (Student s in Students){

     foreach (LogEntry log in LogFile)
    {
        if (log.Student.equals(s) && log.Type.ToString().Equals("Start"))
        {
            TempList.Add(log);
        }
    }
    for (int i = 0; i < TempList.Count; i++) 
    {
        Console.WriteLine("The difference in time is " + TimeDifference(TempList[i].StartTime, Student1StartTimes[i]) + " minutes." );         
    }
    TempList.Clear(); //Clear the temporary list

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-12
    • 2018-05-15
    • 1970-01-01
    • 2010-11-17
    • 1970-01-01
    • 1970-01-01
    • 2021-07-13
    • 2021-06-11
    相关资源
    最近更新 更多