Search for an object in a list without using foreach

I have a list of the next class Student

class student { Guid id; string name; } 

The list contains several students. To find a student with a specific identifier, I need to use the foreach loop and compare the identifier of each student.

I am looking for a better alternative instead of a foreach loop. Is there an affordable alternative?

[EDIT]: What I mean by a better alternative is an optimized solution in terms of runtime and performance

[EDIT2] Another twist if id is Guid.

Thanks,

Frame

+4
source share
6 answers

Nothing will change the fact that you need to iterate over a list. But you can use LINQ:

 List<Student> studentsList = ReadStudentsList(); var student = studentsList.Where(s => s.id == ID_IM_LOOKING_FOR).Single(); 

Based on @Fredrik Mรถrk's answer, this can be shortened to:

 var student = studentsList.Single(s => s.id == ID_IM_LOOKING_FOR); 

Also note that Single() will throw an exception if no students are found. If you prefer to just return null , use SingleOrDefault() .

But what you really want to do is save your students on the map:

 Dictionary<int, Student> students = ReadStudentsMap(); var student = students[ID_IM_LOOKING_FOR]; 

This improves performance (O (1) for hashtables, O (log (n)) for trees) than list browsing (O (n))!

+5
source

If each student can appear in the list only once, you can use Dictionary<int, stutent> . Then you will have a very effective way of finding students by id.

 Dictionary<int, student> students = GetSomeStudents(); // locate student with id = 42 if (students.ContainsKey(42)) { var student = students[42]; // do something useful } 
+6
source

You can use LINQ:

 var student = students.SingleOrDefault(s => s.id == 12); 

Enumerated Method .SingleOrDefault

+2
source

LINQ is an option if you do not want to use foreach lop so that the code is lower

 var student = studentsList.FirstOrDefault(s => s.id == ID_IM_LOOKING_FOR); 
+1
source

Here is an idea to avoid having to iterate over a list:

  • Sort List by Student.Id
  • Implement a more sophisticated search algorithm (e.g. binary search, binary search )
0
source

You can use any collection that uses hash search because their member search is very fast. e.g. Dictionary <K,V> , OrderedDictionary . There is also a non-structural Hashtable , which basically turns out to be redundant with a generic Dictionary<K,V> . In Big-O notation, the time it takes to search for elements by key elements for these O(1) collections is just as good as it gets.

To access the elements, so as not to take the cost of two searches, instead of using ContainsKey you can use the TryGetValue method, for example:

 Dictionary<Guid, Student> students = GetStudents(); Student student; if (students.TryGetValue(guid, out student)) { // found } 

BTW, OrderedDictionary also allows you to access elements by index.

0
source

Source: https://habr.com/ru/post/1401753/


All Articles