Search code examples
c#functionurlslug

How to create unique slugs from unique integers?


I have a table of entities and each has an ID identity column which is a simple incrementing integer, guaranteed to be unique per entity. How can I create relatively short (preferably 10 characters or less) slugs from these identity integers, such that each integer should map to a unique random-looking series of characters in the set [a-z][0-9]? In other words, technically it would be trivial to create slugs that are the string representation of the entities: /foobar/1, /foobar/2, etc. but how can slugs be created based on these identity integers that look more like /foobar/34a4804bc9, /foobar/291e407998, etc.?


Solution

  •         int id = 0;
            Random r = new Random(id);
            char[] chars = "abcdefghijklmnopqrstuvwxyz1234567890".ToCharArray();
            string output = "";
            for (int i = 0; i < 10; i++)
            {
                output += chars[r.Next(chars.Length)];
            }
    
            Console.WriteLine(output);
    

    Is probably the easiest way of doing it. Replace ID with their unique number, it acts as the seed.