I have list of following class Student
class student
{
Guid id;
string name;
}
The list contains multiple students. To search a student with specific id, I need to use foreach loop and compare id of each student.
I am looking for a better alternative instead of foreach loop. Is there any alternative available?
[EDIT]: What I meant by better alternative is optimized solution in terms of execution time and performance
[EDIT2] One more twist, what if id is Guid.
Thanks,
Ram
Nothing will really change the fact that you have to iterate over the list. But you can use LINQ:
Based on an answer by @Fredrik Mörk, this could be shortened to:
Also note, that
Single()will throw an exception, if no student is found. If you’d prefer to just returnnull, useSingleOrDefault().But what you actually want to be doing is storing your students in a map:
This has a way better performance (O(1) for hashtables, O(log(n)) for trees) than looking through the list (O(n))!