Home > Blockchain >  Is there anyway to generate random language shortcode without listing all language shortcodes?
Is there anyway to generate random language shortcode without listing all language shortcodes?

Time:11-30

Is there anyway to generate random language shortcode without listing all language shortcodes in C#? I was thinking about creating list with all short codes and using random to choose the random one, but i need to do it without using list or listing all languages.

Code that i am using:

     var random = new Random();
     var languages = new List<string>{ "en","ak","cz","gu" }; //Many more.., i also need to somehow grab all of them from: https://www.science.co.il/language/Codes.php
     int index = random.Next(languages.Count);
     Console.WriteLine(list[index]);

CodePudding user response:

If you only want to handle the 2-character ISO 639-1 cultures supported by .net, you can do this:

string[] names = 
    CultureInfo.GetCultures(CultureTypes.AllCultures)
    .Select(culture => culture.TwoLetterISOLanguageName)
    .Where(name => name.Length == 2)
    .Distinct()
    .OrderBy(name => name) 
    .ToArray();

That gives the following list of names:

aa af ak am ar as az ba be bg bm bn bo br bs ca ce co cs cu cy da de dv dz ee el en eo es et eu fa ff fi fo fr fy ga gd gl gn gu gv ha he hi hr hu hy ia id ig ii is it iu iv ja jv ka ki kk kl km kn ko ks kw ky lb lg ln lo lt lu lv mg mi mk ml mn mr ms mt my nb nd ne nl nn nr oc om or os pa pl ps pt qu rm rn ro ru rw sa sd se sg si sk sl sn so sq sr ss st sv sw ta te tg th ti tk tn to tr ts tt ug uk ur uz ve vi vo wo xh yi yo zh zu

But note that this is not the full list of language codes.

If you want to include 3-character ISO names, remove the .Where(name => name.Length == 2). Without that filter, the following names are also returned:

agq arn asa ast bas bem bez brx byn ccp ceb cgg chr ckb dav dje dsb dua dyo ebu ewo fil fur gsw guz haw hsb jgo jmc kab kam kde kea khq kkj kln kok ksb ksf ksh lag lkt lrc luo luy mas mer mfe mgh mgo moh mua mzn naq nds nmg nnh nqo nso nus nyn prg quc rof rwk sah saq sbp seh ses shi sma smj smn sms ssy syr teo tig twq tzm vai vun wae wal xog yav zgh

(Let's not worry too much about the fact that TwoLetterISOLanguageName property actually includes a load of 3-character ones...)

  • Related