สร้าง string ที่ไม่ซ้ำด้วย GUID

เมื่อเราทำการเขียนโปรแกรมแล้วต้องการ สร้างชุด string ชุดหนึ่ง เช่น  ID , Username , Password  อื่นๆ เราสามารถสร้างโดย  Globally Unique Identifier (GUID) ของ .Net เอง

GUID มีขนาด 128-bit Interger (16 byte) หากถ้าเราสังเกตุให้ดีๆ ในคอมของเราในส่วนของ Registry จะมีการใช้ GUID ซึ่งใช้เป็นตัวระบุ application IDs  ภายใต้ HKEY_CLASSES_ROOT ใน SQL  Server ได้รวมความสามารถของ GUID ให้เราได้ใช้เป็น data type  (uniqueidentifier) ในการกำหนดค่าของข้อมูลที่เราต้องการให้เป็น GUID  ซึ่งเราสามารถเรียกใช้  function  NEWID() ได้เลย

ใน .Net ได้รวมเอา GUID เข้าไปใน System Class ซึ่งเป็น Base Class ใน  .Net Framework

การสร้าง GUID ในทั้งใน  C# และ VB.NET

1 System.Guid.NewGuid().ToString();

Output ที่ได้ คือ  9245fe4a-d402-451c-b9ed-9c1a04247482

ในทางกลับกันเราสามารถ Convert Output   ซึ่งเป็น string ให้กลับไปเป็น GUID data type ได้โดย

1 System.Guid newid=New Guid(9245fe4a-d402-451c-b9ed-9c1a04247482 );

หรือ

1 System.Guid newid=(SqlGUID.Parse(9245fe4a-d402-451c-b9ed-9c1a04247482 )).Value;

ลักษณะการนำเอาไปใช้นั้นเราสามารถใช้ Guid.ToString() Method   เพื่อกำหนดรูปแบบการแสดงผลได้

Specifier
Format of Return Value
N
32 digits:

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

ตัวอย่าง  newid.ToString(“N”);

9245fe4ad402451cb9ed9c1a04247482

D
32 digits separated by hyphens:

xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

ตัวอย่าง  newid.ToString(“D”);

9245fe4a-d402-451c-b9ed-9c1a04247482

B
32 digits separated by hyphens, enclosed in brackets:

{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}

ตัวอย่าง  newid.ToString(“B”);

{9245fe4a-d402-451c-b9ed-9c1a04247482 }

P
32 digits separated by hyphens, enclosed in parentheses:
ตัวอย่าง  newid.ToString(“P”);

(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)

ตัวอย่าง newid.ToString(“P”);

(9245fe4a-d402-451c-b9ed-9c1a04247482)

นอกจากนั้น  เราสามารถ ย่อ GUID ที่มีขนาดยาวให้เหลือเพียง 16 ตัวอักษร และไม่ซ้ำ

จาก

21726045-e8f7-4b09-abd8-4bcc926e9e28

เป็น

3c4ebc5f5f2c4edc

โดยใช้ function

 1 private string GenerateId()
 2 {
 3  long i = 1;
 4  foreach (byte b in Guid.NewGuid().ToByteArray())
 5  {
 6   i *= ((int)b + 1);
 7  }
 8  return string.Format("{0:x}", i - DateTime.Now.Ticks);
 9 }
10 

ถ้าเราต้องการเอาเฉพาะตัวเลขเท่านั้น

1 private long GenerateId()
2 {
3  byte[] buffer = Guid.NewGuid().ToByteArray();
4  return BitConverter.ToInt64(buffer, 0);
5 }
บันทึกโพสใน โปรเเกรมมิ่ง(Programming). ป้ายกำกับ: . Leave a Comment »

ใส่ความเห็น