Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I have an array, I want to find some element

so I have an array and I want to find some element by some property, just once.
The problem is I am not sure what approach is the best here, I have few options.

  1. First option – Use .ToList().Find()
  2. Second option – Change my array
    to list, but as I said, I am pretty sure I won’t need any other list
    functionality, just one find.
  3. Third option – Find element in array
    by using for loop

Which method is the best and why?

The best, I mean in time and memory optimalization.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This:

var firstMatch = Array.Find(myArray, elem => elem.SomeProperty == someValue);

is functionally equivalent to this:

var firstMatch = myArray.FirstOrDefault(elem => elem.SomeProperty == someValue);

Both will get the first matching element or null if there is no match. If there will definitely be a match then you can use First rather than FirstOrDefault. It will throw an exception if no match is found.

If there may be multiple matches and you want them all then you can call Where instead, which will return an enumerable list that you can run a foreach loop over or else call ToArray or ToList on.

If there must not be more than one match then you can call Single or SingleOrDefault. Where First and FirstOrDefault will stop looking when they find a match, Single and SingleOrDefault will continue looking and throw an exception if another match is found.

It should also be noted that LINQ queries are generally a means to flatten a loop and will perform slightly worse than the corresponding loop. If performance is of utmost importance then you may want to write the more verbose code. LINQ code is generally more readable though, which is generally worth more than the negligible performance gain of the alternative.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading