Best collection to use with type Double as key

后端 未结 4 787
你的背包
你的背包 2020-12-21 14:33

I have this object:

Public Cactus{
    Public Double key;
    Public String value;
}

I have about ~100 Cactus, which all have

4条回答
  •  滥情空心
    2020-12-21 15:25

    I agree with @Mark Byers and @tafa that using the double as the key directly is a bad idea. If you want to make sure that you have exactly the same number you could build a string key based on the bytes that make up the double. The following struct maps a double to the same memory space as 8 bytes so that no custom conversion is needed.

    [StructLayout(LayoutKind.Explicit)]
    public struct TestStruct
    {
        [FieldOffset(0)]
        public byte byte1;
        [FieldOffset(1)]
        public byte byte2;
        [FieldOffset(2)]
        public byte byte3;
        [FieldOffset(3)]
        public byte byte4;
        [FieldOffset(4)]
        public byte byte5;
        [FieldOffset(5)]
        public byte byte6;
        [FieldOffset(6)]
        public byte byte7;
        [FieldOffset(7)]
        public byte byte8;
    
        [FieldOffset(0)]
        public double double1;
    }
    

    It can then wrapped in a function like this (assuming that you have the struct defined in your class as a private variable)

    static string GetStringKey(double key)
    {
        _conversionStruct.double1 = Double.MaxValue;
    
        return String.Format("{0}:{1}:{2}:{3}:{4}:{5}:{6}:{7}", 
            _conversionStruct.byte1,
            _conversionStruct.byte2, 
            _conversionStruct.byte3, 
            _conversionStruct.byte4, 
            _conversionStruct.byte5,
            _conversionStruct.byte6, 
            _conversionStruct.byte7, 
            _conversionStruct.byte8);
    }
    

    And used like this.

    var s1 = GetStringKey(double.MaxValue);
    var s2 = GetStringKey(double.MinValue);
    

    which gives...

    s1="255:255:255:255:255:255:239:127" 
    s2="255:255:255:255:255:255:239:255"
    

提交回复
热议问题