저는 이것을 사용하여 매우 유사한 작업을 수행했습니다. 나는 그것이 거의 사용되지 않는 이벤트와 테이블이 될 것 인 것에 따라 그것의 속력을 걱정할 필요가 없었다. 그러나 필요에 따라 문자열을 증가시킬 수 있습니다.
/// Generates a string and checks for existance
/// <returns>Non-existant string as ID</returns>
public static string GetRandomNumbers(int numChars, string Type)
{
string result = string.Empty;
bool isUnique = false;
while (!isUnique)
{
//Build the string
result = MakeID(numChars);
//Check if unsued
isUnique = GetValueExists(result, Type);
}
return result;
}
/// Builds the string
public static string MakeID(int numChars)
{
string random = string.Empty;
string[] chars = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" };
Random rnd = new Random();
for (int i = 0; i < numChars; i++)
{
random += chars[rnd.Next(0, 35)];
}
return random;
}
/// Checks database tables based on type for existance, if exists then retry
/// <returns>true or false</returns>
private static bool GetValueExists(string value, string Type)
{
bool result = false;
string sql = "";
if (Type == "URL")
{
sql = string.Format(@"IF EXISTS (SELECT COUNT(1) FROM myTable WHERE uniqueString = '{0}')
BEGIN
SELECT 1
END
ELSE
BEGIN
SELECT 0
END ", value);
}
//query the DB to see if it's in use
result = //ExecuteSQL
return result;
}
답변 해 주셔서 감사합니다!나는 질문이있다 : ** 무엇이'encodingBase'인가? ** –
@Maxim - 1 년 전에 기억하기 힘들었지 만, 나는 그것이 인코딩 단어의 길이라고 상상할 것이다. 즉 위의 기본 26 인코딩의 경우 26이됩니다. 그러나 코드에 버그가 있다고 생각합니다. 실제로 1보다 커야합니다. –