Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding object in List without using foreach

Tags:

c#

.net

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

like image 300
Ram Avatar asked Dec 10 '22 01:12

Ram


1 Answers

If each student can appear in the list only once, you might want to use a Dictionary<int, stutent> instead. Then you will have a very efficient way of looking up students by id.

Dictionary<int, student> students = GetSomeStudents();

// locate student with id = 42
if (students.ContainsKey(42))
{
    var student = students[42];
    // do something useful
}
like image 194
Fredrik Mörk Avatar answered Dec 11 '22 15:12

Fredrik Mörk