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.
- First option – Use .ToList().Find()
- 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. - 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.
>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.