I have the following code and want to enhance the performance (maybe with LINQ expressions?).
Anyways, it should search a array for th first item whose field with the name fieldname equals the passed object obj.
For example, lets say we have a array with items of type Person with the fields Name and Age. Now I want to know if my array of 369 persons contains a person with the name “barbara streisand”. Is there a faster way than what I’m doing, or even a way without using a loop?
Heres my code:
public static bool ContainsField<T>(this IEnumerable<T> array, string fieldname, object obj)
{
foreach(T val in array)
{
if (val.GetType().GetField(fieldname).GetValue(val).Equals(obj))
return true;
}
return false;
}
Not without a loop being involved somewhere, no. LINQ makes the code much easier to read, of course.
If all the values in the array will be of the same type, there’s no need to get the field on each iteration of the loop though:
This is using less reflection per iteration, so it’ll be faster than your original, but you could make it faster by creating a delegate from the
Field, to extract the value quickly. The code would end up being a lot more complicated, but probably significantly faster too.Do you definitely have to specify the field name as a string instead of (say) using a lambda expression?