C# 生成唯一id
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11313205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generate a unique id
提问by strange_developer
I am a student at university and our task is to create a search engine. I am having difficulty generating a unique id to assign to each url when added into the frontier. I have attempted using the SHA-256 hashing algorithm as well as Guid. Here is the code that i used to implement the guid:
我是一名大学生,我们的任务是创建一个搜索引擎。当添加到边界时,我很难生成一个唯一的 id 来分配给每个 url。我曾尝试使用 SHA-256 散列算法以及 Guid。这是我用来实现guid的代码:
public string generateID(string url_add)
{
long i = 1;
foreach (byte b in Guid.NewGuid().ToByteArray())
{
i *= ((int)b + 1);
}
string number = String.Format("{0:d9}", (DateTime.Now.Ticks / 10) % 1000000000);
return number;
}
采纳答案by Jaime Torres
Why not just use ToString?
为什么不直接使用 ToString?
public string generateID()
{
return Guid.NewGuid().ToString("N");
}
If you would like it to be based on a URL, you could simply do the following:
如果您希望它基于 URL,您可以简单地执行以下操作:
public string generateID(string sourceUrl)
{
return string.Format("{0}_{1:N}", sourceUrl, Guid.NewGuid());
}
If you want to hide the URL, you could use some form of SHA1 on the sourceURL, but I'm not sure what that might achieve.
如果你想隐藏 URL,你可以在 sourceURL 上使用某种形式的 SHA1,但我不确定这可能会实现什么。
回答by abatishchev
回答by daz-fuller
If you want to use sha-256 (guid would be faster) then you would need to do something like
如果你想使用 sha-256(guid 会更快),那么你需要做类似的事情
SHA256 shaAlgorithm = new SHA256Managed();
byte[] shaDigest = shaAlgorithm.ComputeHash(ASCIIEncoding.ASCII.GetBytes(url));
return BitConverter.ToString(shaDigest);
Of course, it doesn't have to ascii and it can be any other kind of hashing algorithm as well
当然,它不必是ascii,也可以是任何其他类型的散列算法
回答by Tom
This question seems to be answered, however for completeness, I would add another approach.
这个问题似乎得到了回答,但是为了完整起见,我会添加另一种方法。
You can use a unique ID number generator which is based on Twitter's Snowflakeid generator. C# implementation can be found here.
您可以使用基于 Twitter 的Snowflakeid 生成器的唯一 ID 号生成器。C# 实现可以在这里找到。
var id64Generator = new Id64Generator();
// ...
public string generateID(string sourceUrl)
{
return string.Format("{0}_{1}", sourceUrl, id64Generator.GenerateId());
}
Note that one of very nice features of that approach is possibility to have multiple generators on independent nodes (probably something useful for a search engine) generating real time, globally unique identifiers.
请注意,该方法的一个非常好的特性是可以在独立节点上拥有多个生成器(可能对搜索引擎有用)生成实时的全局唯一标识符。
// node 0
var id64Generator = new Id64Generator(0);
// node 1
var id64Generator = new Id64Generator(1);
// ... node 10
var id64Generator = new Id64Generator(10);
回答by Jineesh Uvantavida
Why can't we make a unique id as below.
为什么我们不能创建一个唯一的 id,如下所示。
We can use DateTime.Now.Ticks and Guid.NewGuid().ToString() to combine together and make a unique id.
我们可以使用 DateTime.Now.Ticks 和 Guid.NewGuid().ToString() 组合在一起,形成一个唯一的 id。
As the DateTime.Now.Ticks is added, we can find out the Date and Time in seconds at which the unique id is created.
添加 DateTime.Now.Ticks 后,我们可以找出创建唯一 id 的日期和时间(以秒为单位)。
Please see the code.
请看代码。
var ticks = DateTime.Now.Ticks;
var guid = Guid.NewGuid().ToString();
var uniqueSessionId = ticks.ToString() +'-'+ guid; //guid created by combining ticks and guid
var datetime = new DateTime(ticks);//for checking purpose
var datetimenow = DateTime.Now; //both these date times are different.
We can even take the part of ticks in unique id and check for the date and time later for future reference.
我们甚至可以在唯一 id 中提取刻度部分,然后检查日期和时间以供将来参考。
回答by Ashraf Ali
Here is a 'YouTube-video-id' like id generator e.g. "UcBKmq2XE5a"
这是一个类似于 id 生成器的“YouTube-video-id”,例如“UcBKmq2XE5a”
StringBuilder builder = new StringBuilder();
Enumerable
.Range(65, 26)
.Select(e => ((char)e).ToString())
.Concat(Enumerable.Range(97, 26).Select(e => ((char)e).ToString()))
.Concat(Enumerable.Range(0, 10).Select(e => e.ToString()))
.OrderBy(e => Guid.NewGuid())
.Take(11)
.ToList().ForEach(e => builder.Append(e));
string id = builder.ToString();
It creates random ids of size 11 characters. You can increase/decrease that as well, just change the parameter of Take method.
它创建大小为 11 个字符的随机 ID。您也可以增加/减少它,只需更改 Take 方法的参数即可。
0.001% duplicates in 100 million.
0.001% 重复 1 亿。
回答by Mohsin Khan
We can do something like this
我们可以做这样的事情
string TransactionID = "BTRF"+DateTime.Now.Ticks.ToString().Substring(0, 10);

