c# compare different unsorted arrays

时间:2016-07-11 20:31:59

标签: c# arrays list compare

I'm still a beginner in C# and I haven't found a solution that fixes my issue.

I've made this a couple of months ago and it worked well enough until now, but I can foresee some problems in the future when the group gets larger. I have a log file that contains all kind of stuff, but I'm only interested in the "start" and "stop" times of all students. Each week I run this code to check if everyone started and stopped at the correct times. Not all students come in each day: some only have 3 start and 3 stop entries per week, some have 4 or 5. I have made arrays with reference values for each student (for example Student1StartTimes).

Right now the code scans the logfile twice for entries of a particular student. Once for their start times and once for their stop times. These get placed in a temporary array and get compared to their reference values. They don't have to match exactly, a few minutes off is fine. The order of the entries of a particular student is important since their start/stop times can depend on the day they were entered.

An example is shown below. As said before, it seems to work for my purpose but as the amount of students increases so does the amount of for loops, and I feel this could be done much more efficiently.

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

1 个答案:

答案 0 :(得分:0)

Do you store the student in a collection?

If so loop through each student, within the student loop you can then loop through the log:

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

}