Get Enum name based on Enum value

I declared the following Enum:

public enum AfpRecordId { BRG = 0xD3A8C6, ERG = 0xD3A9C6 } 

and I want to get an enumeration object from a 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 equal performance.

+6
source share
3 answers

Plain:

  • Convert the byte array to int (either manually or by creating an array of four bytes, and using BitConverter.ToInt32 )
  • Move int to AfpRecordId
  • Call ToString on the result, if necessary (the subject line offers to get a name, but your method signature says only about the value)

For instance:

 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 if the data is really a valid identifier.

As far as performance is concerned, make sure that something simple gives you reasonably good performance before looking for something faster.

+9
source

If the array has a known size (I assume that size 3 matches your example), you can add the elements together and pass the result to an enumeration

 private AfpRecordId GetAfpRecordId(byte[] tempData){ var temp = tempData[0] * 256*256 + tempData[1] * 256 +tempData[2]; return (AfpRecordId)temp; } 

another approach would be to use the shift operator instead

 private AfpRecordId GetAfpRecordId(byte[] tempData){ var temp = (int)tempData[0]<<16 + (int)tempData[1] * 8 +tempData[2]; return (AfpRecordId)temp; } 
+1
source

Assuming tempData has 3 elements, use Enum.GetName (typeof (AfpRecordId), tempData[0] * 256*256 + tempData[1] * 256 +tempData[2]) .

+1
source

Source: https://habr.com/ru/post/900604/


All Articles