views:

866

answers:

2

Hi there,

I have a byte array and wish to find the first occurance (if any) of a specific byte.

Can you guys help me with a nice, elegant and efficient way to do it?

 /// Summary
/// Finds the first occurance of a specific byte in a byte array.
/// If not found, returns -1.
public int GetFirstOccurance(byte byteToFind, byte[] byteArray)
{

}
+11  A: 
public static int GetFirstOccurance(byte byteToFind, byte[] byteArray)
{
   return Array.IndexOf(byteArray,byteToFind);
}

It will return -1 if not found

Or as Sam pointed out, an extension method:

public static int GetFirstOccurance(this byte[] byteArray, byte byteToFind)
{
   return Array.IndexOf(byteArray,byteToFind);
}

Or to make it generic:

public static int GetFirstOccurance<T>(this T[] array, T element)
{
   return Array.IndexOf(array,element);
}

Then you can just say:

int firstIndex = byteArray.GetFirstOccurance(byteValue);
Philippe Leybaert
You could make this a static method!
Samuel Jack
I meant to say, extension method, of course.
Samuel Jack
Indeed. Changed it...
Philippe Leybaert
extension method too, but only in C# 3.0
Philippe Leybaert
Thanks for the time taken to answer activa - i will be using your extension mothod.
divinci
+5  A: 

Array.IndexOf?

Greg Beech