I often work with arrays of int/float and other things on a regular basis in C# since they are faster (maybe?) than List. Currently I’ve got dozens of functions implemented per type:
/// <summary>
/// Checks if the array contains the given value.
/// </summary>
public static bool contains(int[] values, int value) {
for (int s = 0, sl = values.Length; s < sl; s++) {
if (values[s] == value) {
return true;
}
}
return false;
}
/// <summary>
/// Checks if the array contains the given value.
/// </summary>
public static bool contains(float[] values, float value) {
for (int s = 0, sl = values.Length; s < sl; s++) {
if (values[s] == value) {
return true;
}
}
return false;
}
Is there a way to implement these in a generic way? Or is that only possible if I use List<T>?
The
System.Arraytype has a dizzying array of static methods that can help you search, arrange, sort etc your arrays. You definitely do not need to roll your own. These static methods (likeFind,FindAll) also accept generic arguments. Here’s the list, dumped with the aid of PowerShell: