开发者

A class for efficient key generation

开发者 https://www.devze.com 2023-02-05 19:03 出处:网络
So, I am looking into efficient ways of generating a unique key that is based on an integer array and can be stored in a database column.

So, I am looking into efficient ways of generating a unique key that is based on an integer array and can be stored in a database column.

In the old days of C, I could just create a copy of the memory location of the array and return it as a string, which would then serve as my key. I do not know if can still do that in C#, but I am looking ways (nearly) as efficient as this one. Any suggestions?

Thanks, Kemal

UPDATE: What I meant is that the result should be unique depending on the elements of the input array. So, the GUID suggestion is not applicable here. One obvious solution is to concatenate the text versions of the array elements into a string, as was suggested by Jon Benedicto. What I was looking was something that is very efficient to execute. I myself come up with the following code after looking into the unsafe code section in the language reference of C#:

    public static string BuildKey( int[ ] src ) {
        string res;
        unsafe {
            fixed( int* fxsrc = src ) {
                res 开发者_开发技巧= new string( ( char* )fxsrc, 0, src.Length*2 );
            }
        }
        return res;
    }       

Is there any problems with that code?


var pk = Guid.NewGuid();

// Or if you need it as a string
var pkAsString = pk.ToString();

How more unique do you need it?


If you have an integer array in C# that you want converted, you can use the ConvertAll static generic method on the Array class to convert the integers to a string representation:

int[] data = { 0, 1, 2, 3, 4, 5, 6 };

string value = String.Join(",", Array.ConvertAll<int, string>(data, x => x.ToString()));
0

精彩评论

暂无评论...
验证码 换一张
取 消