如何在C#中创建一个独特的随机字符序列?

hol*_*ira 6 c# string random

我正在我的应用程序中实现URL缩短功能,以便为我的用户提供可在Twitter中使用的更短的替代URL.关键是要独立于提供同样服务的缩短服务,并将其作为我的网络应用程序的一项功能.

创建一个大约6个字符的独特随机字符序列的最佳方法是什么?我计划将其用作我的数据库中具有备用URL的项目的索引.

编辑:

此功能将用于工作板网站,其中每个新的工作广告都将获得带有标题的自定义URL以及要在Twitter中使用的较短的URL.也就是说,长期以来,独特的6个字符组合的总数将绰绰有余.

Kir*_*rst 3

你真的需要“随机”,还是“唯一”就足够了?

Unique 非常简单 - 只需将 URL 插入数据库,然后将该记录的顺序 id 转换为由您选择的字符集表示的基数 n 数字。

例如,如果您只想在序列中使用 [AZ],则可以将记录的 id 转换为基数 26 数字,其中 A=1、B=2、... Z=26。该算法是递归 div26/mod26,其中商是所需的字符,余数用于计算下一个字符。

然后,在检索 URL 时,执行逆函数,即将 26 进制数转换回十进制。执行 SELECT URL WHERE ID =decimal,就完成了!

编辑:

private string alphabet = "abcdefghijklmnopqrstuvwxyz"; 
   // or whatever you want.  Include more characters 
   // for more combinations and shorter URLs

public string Encode(int databaseId)
{
    string encodedValue = String.Empty;

    while (databaseId > encodingBase)
    {
        int remainder;
        encodedValue += alphabet[Math.DivRem(databaseId, alphabet.Length, 
            out remainder)-1].ToString();
        databaseId = remainder;
    }
    return encodedValue;
}

public int Decode(string code)
{
    int returnValue;

    for (int thisPosition = 0; thisPosition < code.Length; thisPosition++)
    {
        char thisCharacter = code[thisPosition];

        returnValue += alphabet.IndexOf(thisCharacter) * 
            Math.Pow(alphabet.Length, code.Length - thisPosition - 1);
    }
    return returnValue;
}
Run Code Online (Sandbox Code Playgroud)