C # method Rollup for generating unique values

Source: Internet
Author: User

One, build in. NET

1, using the Guid () function provided directly by the. NET Framework, this method is very widely used. A GUID (Global uniform identifier) is a number generated on a single machine that guarantees that no duplicate GUID values are generated for any two computers in the same space-time (that is, all machines are guaranteed to be unique). The introduction of GUIDs is not a specific statement here, so you can check out MSDN yourself for a closer look. The code is as follows:

The code is as follows:
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;

Namespace ConsoleApplication1
{
Class Program
{
static void Main (string[] args)
{
String _guid = GetGuid ();
Console.WriteLine ("Unique code: {0}\t Length: {1}\n Remove connector: {2}", _guid, _guid.) Length, _guid. Replace ("-", ""));

String uniqueidstring = Guidto16string ();
Console.WriteLine ("Unique code: {0}\t length: {1}", uniqueidstring, Uniqueidstring.length);

Long Uniqueidlong = Guidtolongid ();
Console.WriteLine ("Unique code: {0}\t length: {1}", Uniqueidlong, Uniqueidlong.tostring (). Length);

}

<summary>
32-digit number separated by hyphens
</summary>
<returns></returns>
private static string GetGuid ()
{
System.Guid GUID = new GUID ();
GUID = Guid.NewGuid ();
The return GUID. ToString ();
}

<summary>
Gets a unique 16-bit string based on the GUID
</summary>
<param name=\ "guid\" ></param>
<returns></returns>
public static string Guidto16string ()
{
Long i = 1;
foreach (Byte b in Guid.NewGuid (). Tobytearray ())
I *= ((int) b + 1);

return string. Format ("{0:x}", i-datetime.now.ticks);
}

<summary>
Gets a 19-bit unique number sequence based on a GUID
</summary>
<returns></returns>
public static long Guidtolongid ()
{
byte[] buffer = Guid.NewGuid (). Tobytearray ();
Return Bitconverter.toint64 (buffer, 0);
}

}
}

2. Generated with DateTime.Now.ToString ("Yyyymmddhhmmssms") and the RNGCryptoServiceProvider () provided by the. NET Framework, the code is as follows:

The code is as follows:
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;

Using System.Threading;

Namespace ConsoleApplication1
{
Class Program
{
static void Main (string[] args)
{
String uniquenum = Generateordernumber ();
Console.WriteLine ("Unique code: {0}\t length: {1}", Uniquenum, Uniquenum.length);

Tests whether duplicates are generated
Console.WriteLine ("Time +rngcryptoserviceprovider () combines the generated unique values, as follows:");
String _tempnum = String. Empty;
for (int i = 0; i <; i++)
{
String uNum = Generateordernumber ();
Console.WriteLine (UNum);
if (string. Equals (UNum, _tempnum))
{
Console.WriteLine ("Duplicate on value exists, press ENTER to continue");
Console.readkey ();
}

The current thread of sleep is for inertia, and thus does not produce duplicate values. You can comment it out and test it.
Thread.Sleep (300);

_tempnum = UNum;
}

}

<summary>
Unique order number generation
</summary>
<returns></returns>
public static string Generateordernumber ()
{
String strdatetimenumber = DateTime.Now.ToString ("yyyymmddhhmmssms");
String strrandomresult = Nextrandom (1000, 1). ToString ();

return strdatetimenumber + Strrandomresult;
}

<summary>
Reference: RNGCryptoServiceProvider examples on MSDN
</summary>
<param name= "Numseeds" ></param>
<param name= "Length" ></param>
<returns></returns>
private static int nextrandom (int numseeds, int length)
{
Create a byte array to hold the random value.
byte[] Randomnumber = new Byte[length];
Create a new instance of the RNGCryptoServiceProvider.
System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider ();
Fill the array with a random value.
Rng. GetBytes (Randomnumber);
Convert the byte to a uint value to make the modulus operation easier.
UINT Randomresult = 0x0;
for (int i = 0; i < length; i++)
{
Randomresult |= (UINT) randomnumber[i] << ((length-1-i) * 8));
}

return (int) (randomresult% numseeds) + 1;
}
}
}

3. Use [0-9a-z] + guid.newguid () to combine a unique string that generates a specific number of digits, with the following code:

The code is as follows:
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;

Namespace ConsoleApplication1
{
Class Program
{
static void Main (string[] args)
{
String uniquetext = Generateuniquetext (8);
Console.WriteLine ("Unique code: {0}\t length: {1}", Uniquetext, Uniquetext.length);

Tests whether duplicates are generated
Console.WriteLine ("A unique value generated by [0-9a-z] + newguid (), as follows:");
ilist<string> list = new list<string> ();
for (int i = 1; i <=; i++)
{
String _ut = Generateuniquetext (8);
Console.WriteLine ("{0}\t{1}", List. Count, _ut);
if (list. Contains (_ut))
{
Console.WriteLine ("{0} value is duplicated", _ut);
Console.readkey ();
}

List. ADD (_ut);

if (i% 200 = = 0)
//{
Console.WriteLine ("No duplicates, press the ENTER key to look down");
Console.readkey ();
//}
}

List. Clear ();
}

<summary>
A unique string that generates a specific number of digits
</summary>
<param name= "num" > specific number of digits </param>
<returns></returns>
public static string generateuniquetext (int num)
{
String Randomresult = String. Empty;
String readystr = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char[] Rtn = new Char[num];
Guid gid = Guid.NewGuid ();
var ba = gid. Tobytearray ();
for (var i = 0; i < num; i++)
{
Rtn[i] = readystr[((Ba[i] + ba[num + i])% 35)];
}

foreach (char R in RTN)
{
Randomresult + = r;
}

return randomresult;
}

}
}

4, with a single example of the implementation of the [0-9a-z] combination of the unique values generated, this article does not discuss the singleton mode of the implementation of a variety of ways and performance problems, casually get a way to achieve, the code is as follows:

Program.cs Program:

The code is as follows:
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;

Using System.Collections;
Using System.Xml;

Namespace ConsoleApplication4
{
Class Program
{
static void Main (string[] args)
{
Createid Createid = Createid.getinstance ();

Tests whether duplicates are generated
Console.WriteLine ("Singleton mode implementation, the unique value generated by the [0-9a-z] combination, as follows:");
ilist<string> list = new list<string> ();
for (int i = 1; I <= 1000000000; i++)
{
String struniquenum = Createid.createuniqueid ();
Console.WriteLine ("{0}\t{1}", List. Count, Struniquenum);
if (list. Contains (Struniquenum))
{
Console.WriteLine ("{0} value is duplicated", struniquenum);
Console.readkey ();
}

List. ADD (Struniquenum);

if (i% 200 = = 0)
{
Console.WriteLine ("No duplicates, press the ENTER key to look down");
Console.readkey ();
}
}

List. Clear ();
}
}

<summary>
Single-Instance mode implementation
Unique values are combined by [0-9a-z] and each generated ID cannot be duplicated
</summary>
public class Createid
{
private static Createid _instance;
private static readonly Object syncRoot = new Object ();
Private ehashtable hashtable = new ehashtable ();
private string _strxmlurl = String. Empty;

Private Createid ()
{
Hashtable. ADD ("0", "0");
Hashtable. ADD ("1", "1");
Hashtable. ADD ("2", "2");
Hashtable. ADD ("3", "3");
Hashtable. ADD ("4", "4");
Hashtable. ADD ("5", "5");
Hashtable. ADD ("6", "6");
Hashtable. ADD ("7", "7");
Hashtable. ADD ("8", "8");
Hashtable. ADD ("9", "9");
Hashtable. ADD ("Ten", "a");
Hashtable. ADD ("One", "B");
Hashtable. Add ("n", "C");
Hashtable. ADD ("+", "D");
Hashtable. ADD ("+", "E");
Hashtable. ADD ("All", "F");
Hashtable. ADD ("+", "G");
Hashtable. Add ("n", "H");
Hashtable. ADD ("+", "I");
Hashtable. ADD ("+", "J");
Hashtable. ADD ("A", "K");
Hashtable. ADD ("+", "L");
Hashtable. ADD ("A", "M");
Hashtable. ADD ("All", "n");
Hashtable. ADD ("+", "O");
Hashtable. ADD ("+", "P");
Hashtable. ADD ("+", "Q");
Hashtable. Add ("n", "R");
Hashtable. ADD ("+", "s");
Hashtable. ADD ("+", "T");
Hashtable. ADD ("V", "U");
Hashtable. ADD ("+", "V");
Hashtable. ADD ("+", "w");
Hashtable. Add ("×", "X");
Hashtable. ADD ("The", "Y");
Hashtable. ADD ("+", "Z");
_strxmlurl = System.IO.Path.GetFullPath (@ "). \.. \ ") +" Xmls\\record.xml ";

}

public static Createid getinstance ()
{
if (_instance = = null)
{
Lock (SyncRoot)
{
if (_instance = = null)
{
_instance = new Createid ();
}
}
}

return _instance;
}

<summary>
Create UniqueID
</summary>
<returns>UniqueID</returns>
public string Createuniqueid ()
{
Long _uniqueid = Getguidfromxml ();

Return convert10to36 (_uniqueid);
}

<summary>
Gets the UniqueID total record, that is, gets the ID of the number that is obtained
Update the number of UniqueID used for the next use
</summary>
<returns></returns>
Private Long Getguidfromxml ()
{
Long record = 0;
XmlDocument xmldoc = new XmlDocument ();
XmlDoc. Load (_strxmlurl);
XmlElement RootNode = xmldoc. DocumentElement;
The value of this number
Record = Convert.toint64 (rootnode["record"). InnerText);
The number of this time is +1 = = The next number of values
Rootnode["Record"]. InnerText = convert.tostring (record + 1);
XmlDoc. Save (_strxmlurl);

return record;
}

<summary>
10-in-turn 36-in system
</summary>
<param name= "INTNUM10" >10 binary number </param>
<returns></returns>
private string convert10to36 (long INTNUM10)
{
String strNum36 = String. Empty;
Long result = INTNUM10/36;
Long remain = intNum10% 36;
if (Hashtable. ContainsKey (remain. ToString ()))
STRNUM36 = Hashtable[remain. ToString ()]. ToString () + strNum36;
INTNUM10 = result;
while (INTNUM10/36! = 0)
{
result = INTNUM10/36;
remain = intNum10% 36;
if (Hashtable. ContainsKey (remain. ToString ()))
STRNUM36 = Hashtable[remain. ToString ()]. ToString () + strNum36;
INTNUM10 = result;
}
if (intNum10 > 0 && INTNUM10 < 36)
{
if (Hashtable. ContainsKey (Intnum10.tostring ()))
STRNUM36 = Hashtable[intnum10.tostring ()]. ToString () + strNum36;
}

return STRNUM36;
}

}

<summary>
Summary description for Ehashtable
</summary>
public class Ehashtable:hashtable
{
Private ArrayList list = new ArrayList ();
public override void Add (object key, Object value)
{
Base. ADD (key, value);
List. ADD (key);
}
public override void Clear ()
{
Base. Clear ();
List. Clear ();
}
public override void Remove (object key)
{
Base. Remove (key);
List. Remove (key);
}
public override ICollection Keys
{
Get
{
return list;
}
}
}

}

Xml:

The code is as follows:
<?xml version= "1.0" encoding= "Utf-8"?>
<root>
<record id= "Record" >1</record>
</root>

Second, the generation of GUIDs in JS, similar. NET Guid.NewGuid (), the code is as follows:

Copy the code code as follows:
function NewGuid () {//Method one:
var guid = "";
var n = (((1 + math.random ()) * 0x10000) | 0). toString (+). substring (1);
for (var i = 1; I <= 8; i++) {
GUID + = n;
}
return GUID;
}

function NewGuid () {//Method two:
var guid = "";
for (var i = 1; i <=; i++) {
var n = math.floor (Math.random () * 16.0). toString (16);
GUID + = n;
if ((i = = 8) | | (i = = 12) | | (i = = 16) | | (i = = 20))
GUID + = "-";
}
return GUID;
}

C. Generate the GUID in the SQL stored procedure, with the following code:

Copy the code code as follows:
-- =============================================
--AUTHOR:WANGWS
--Create date:2015-06-05
--Description: Generates a unique identity ID, a public stored procedure that can be set to call this stored procedure in another stored procedure to pass a different prefix
-- =============================================
ALTER PROCEDURE [dbo]. [Pro_createguid]
@Prefix NVARCHAR (10),
@outputV_guid NVARCHAR (+) OUTPUT
As
BEGIN
--SET NOCOUNT on added to prevent extra result sets from
--interfering with SELECT statements.
SET NOCOUNT on;

--Insert statements for procedure here
SET @outputV_guid = @Prefix + REPLACE (CAST (NEWID () as VARCHAR (36)), '-', ')
END

C # method Rollup for generating unique values

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.