Created
October 31, 2019 13:31
-
-
Save jonfuller/e4b580a8c586ed274cea33938151e31a to your computer and use it in GitHub Desktop.
Generate some readable IDs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class IdGenerator | |
{ | |
private static readonly ConcurrentDictionary<string, IEnumerator<string>> _generators = new ConcurrentDictionary<string, IEnumerator<string>>(); | |
public static string Next(string prefix) | |
{ | |
var generator = _generators.GetOrAdd(prefix, x => MakeSequence(prefix).GetEnumerator()); | |
generator.MoveNext(); | |
return generator.Current; | |
} | |
public static IEnumerable<string> MakeSequence(string prefix) | |
{ | |
var letters = Enumerable.Range(0, 26) | |
.Select(i => new string((char)(i + 'A'), 1)) | |
.ToList(); | |
var doubleLetters = | |
from x in letters | |
from y in letters | |
select $"{x}{y}"; | |
var tripleLetters = | |
from x in letters | |
from y in letters | |
from z in letters | |
select $"{x}{y}{z}"; | |
var sequence = letters.Concat(doubleLetters).Concat(tripleLetters); | |
foreach (var item in sequence) | |
{ | |
yield return $"{prefix}{item}"; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment