When you do this:
student.Grade = grades.Single(x => x.StudentId == student.Id).Value;
As indicated, it should list the entire List until it finds an entry in the list that has the correct studentId (does entry 0 match lambda? No ... Does entry 1 fit into lambda? No ... etc.). This is O (n). Since you do this once for each student, this is O (n ^ 2).
However, when you do this:
student.Grade = dic[student.Id];
If you want to find a specific element by the key in the dictionary, it can instantly go where it is in the dictionary - this is O (1). O (n) for this for each student. (If you want to know how this is done, the dictionary performs a mathematical operation on the key, which turns it into a value, which is the place inside the dictionary, which is the same place that it placed when it was inserted)
So, the dictionary is faster because you used the best algorithm.
Patashu Jun 07 '13 at 6:38 2013-06-07 06:38
source share