0

I have an application that uses multiple different phrases, given a certain situation. I want to put these phrases into a resource file to enable localization. At runtime, I want to be able to pick one of the N strings to display, randomly.

As an example, say i was displaying a greeting phrase to the user. I might have the following phrases as a greeting variant.

  1. Hello
  2. Hey there
  3. Welcome

Now i know i can store them in my resource file, given it is a key/value pair.

  1. GreetingVariant0
  2. GreetingVariant1
  3. GreetingVariant2

How can i pick one of these randomly at run time?

Do i need to have a config file, store the number of "Greeting Variants", read in that config file, and then pick a random number, and then pull that resource?

Is there a better way?

NiteLordz
  • 597
  • 2
  • 18

1 Answers1

0

I would personally probably use the configuration solution because retrieving the resources would then be quite easy by just appending a random number from the given range to the resource key prefix and retrieving the resource by key.

Another option could be to query all keys in the resource file (using one of the solutions here) and select those with the given prefix using LINQ. The you can just select a random one from the resulting set. Of course, this solution is less efficient, as it requires a loop over all existing resources.

Martin Zikmund
  • 38,440
  • 7
  • 70
  • 91
  • I don't like the idea of concatenating a random string to a predefined key prefix. What if he adds more values, how do you know what the max number your Random should generate is? – p3tch Jul 17 '18 at 12:46
  • First solution on it's own will take maintenance, but look at the link he provided in the second one, it contains a method of iterating through all resources, which enables you to count relevant ones. – Zero Jul 17 '18 at 12:47
  • Thats what the configuration value would be used for in the first solution, and the enumeration in the second – Martin Zikmund Jul 17 '18 at 12:47
  • That's his other option @Zero, I'm referring to his first suggestion – p3tch Jul 17 '18 at 12:49
  • I understand it is not ideal, but it seems to me as the better option of the two... You could write a unit test that verifies that the resources with the prefix + id are available for the range set in the configuration. – Martin Zikmund Jul 17 '18 at 13:02