在 C# 中剪切 GUID 并像这样制作 GP-(6CharacterOFGUID)-000001

Cut the GUID in C# and Make Like This GP-(6CharacterOFGUID)-000001

你好我正在创建一个自动生成的 ID,第一个字符串是 GP,6 个字符是 GUID,auto_increment 000001 取决于 ID。所以它会是这样的

GP-FJISLD-00001

这是我生成的 GUID 字符串。它执行 32 GUID,这在我尝试通过搜索主键查找数据时不是很好。

String GUID = System.Guid.NewGuid().ToString().Replace("-", "").ToUpper();
txt_ouput.Text = GUID.ToString();

有什么帮助吗?谢谢 :D

您是否尝试过 string.Substring 伪随机化方法?

int id = yourId;
int pseudoRandomizerStart = (yourId % 32) - 1; //32 is the length of a Guid, -1 to make sure it lands on the correct index.
string firstSixGuidChars = GUID.Substring(pseudoRandomizerStart, pseudoRandomizerStart + 5); //this is based on index.
string idString = id.ToString();

//Hypothetically, you want your id to be, at minimum 6 digits long, 
//with preceding 0s if the number is less than 6 digits 
//and the whole number if it's more than 6 digits.
if(idString.Length < 6){
idString = "000000" + idString;
idString = idString.Substring(idString.Length - 6);
}

所以理论上,id 00001会生成Guid的前六个字符,00002会生成Guid的索引1到6,依此类推。如果您的 ID 是唯一的,那么这应该总是 return 一个唯一的键。

然后它将获取您的 ID,根据您的需要在其前面附加零,然后 return 返回一个六位数的 ID 给您(如果数字少于 6 位,则在前面加上零。 )

这个和你的例子的唯一问题是 Guid returns 32 个十六进制数字,所以我不能保证 Guid return 是一个全字母部分(基于你的例子) .

通过只使用 GUID 的前六个字符,我会对它的独特性持保留意见...

在我看来,您实际上想在这里做的是拥有一个复合键,涉及类型、ID 和序列号。

我的建议是单独基于 ID(完整 GUID)实现主键,然后将其他字段放在非聚集索引上。