Converting System.Decimal to System.Guid

前端 未结 4 1329
南笙
南笙 2020-12-06 11:35

I have a big dictionary where the key is decimal, but the GetHashCode() of System.Decimal is disasterously bad. To prove my guess, I ran a for loop with 100.000 neigboring d

4条回答
  •  隐瞒了意图╮
    2020-12-06 12:33

    Convert your decimal value to byte array, and then create a guid from it:

    public static byte[] DecimalToByteArray (decimal src) 
    {
        using (MemoryStream stream = new MemoryStream()) 
        {
            using (BinaryWriter writer = new BinaryWriter(stream))
            {
                writer.Write(src);
                return stream.ToArray();
            }
        }
    }
    
    Decimal myDecimal = 1234.5678M;
    Guid guid = new Guid(DecimalToByteArray(myDecimal));
    

提交回复
热议问题