I have declared the following Enum:
public enum AfpRecordId
{
BRG = 0xD3A8C6,
ERG = 0xD3A9C6
}
and i want to retrieve the enum object from is value:
private AfpRecordId GetAfpRecordId(byte[] data)
{
...
}
Call Examples:
byte[] tempData = new byte { 0xD3, 0xA8, 0xC6 };
AfpRecordId tempId = GetAfpRecordId(tempData);
//tempId should be equals to AfpRecordId.BRG
I would also like to use linq or lambda, only if they can give better or equals performance.
Simple:
int
(either manually, or by creating a four byte array and using BitConverter.ToInt32
)int
to AfpRecordId
ToString
on the result if necessary (your subject line suggests getting the name, but your method signature only talks about the value)For example:
private static AfpRecordId GetAfpRecordId(byte[] data)
{
// Alternatively, switch on data.Length and hard-code the conversion
// for lengths 1, 2, 3, 4 and throw an exception otherwise...
int value = 0;
foreach (byte b in data)
{
value = (value << 8) | b;
}
return (AfpRecordId) value;
}
You can use Enum.IsDefined
to check whether the given data is actually a valid ID.
As for performance - check whether something simple gives you good enough performance before you look for something faster.
Assuming that tempData
has 3 elements use Enum.GetName (typeof (AfpRecordId), tempData[0] * 256*256 + tempData[1] * 256 +tempData[2])
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With