如何为自动生成创建自定义Guid? [英] How to create custom Guid for auto Generation ?

查看:327
本文介绍了如何为自动生成创建自定义Guid?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要自动生成的学生入学号码,我使用的是Guid,但它是非常大的随机数



i只需要前4个值字母下一个8个数字

请帮助?



Guid id = Guid.NewGuid();

i need Student Admission number in auto generation i used Guid but it's very large random numbers

i need only first 4 values letters next 8 numbers
pls help ?

Guid id = Guid.NewGuid();

推荐答案

你可以这样做。



You can do something like this.

var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
var nums = "0123456789";
var stringChars = new char[4];
var stringNums = new char[8];
var random = new Random();

for (int i = 0; i < stringChars.Length; i++)
    stringChars[i] = chars[random.Next(chars.Length)];
for (int i = 0; i < stringNums.Length; i++)
    stringNums[i] = nums[random.Next(nums.Length)];
var finalString = new char[stringChars.Length + stringNums.Length];
stringChars.CopyTo(finalString, 0);
stringNums.CopyTo(finalString, stringChars.Length);





上面给出的代码块将为您提供一个随机字符串,其中包含4个字母,后跟8个数字。 finalString 包含生成的字符串。希望这会有所帮助。





-Subho



The code block presented above will give you a randomized string with 4 alphabets followed by 8 numbers. finalString contains the generated string. Hope this helps.


-Subho


static class StringExt {

public static IEnumerable<String> SplitInParts(this String s, Int32 partLength) {

    for (var i = 0; i < s.Length; i += partLength)
      yield return s.Substring(i, Math.Min(partLength, s.Length - i));
  }
}
var parts = System.Guid.NewGuid().ToString().Replace("-","").SplitInParts(4);



但请记住保留唯一性需要有16位数字。您也可以使用guid.ToString(N)来获取没有' - '的数字,请尝试使用它为目的制作的整个GUID。 :)

请尝试这个并回复你的评论如果有效。

谢谢。


But remember for retaining the uniqueness you need to have the 16 digits. You can also use guid.ToString("N") for getting number without '-', please try and use the whole GUID it is made for a purpose. :)
Please try this and post back your comments if this works out.
Thanks.


如果你真的需要一个GUID ,这是一个 全球唯一标识符 [ ^ ],那么你必须保留它的全部长度。

另一方面,如果您的要求不是那么严格(例如,您可以放弃'全局'要求),那么您可以生成更短的随机ID。
If you really need a GUID, that is a Global Unique Identifier [^], then you have to retain all its length.
On the other hand, if your requirements aren't so strict (e.g. you can drop the 'global' requirement) then you may generate a shorter random id.


这篇关于如何为自动生成创建自定义Guid?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆