Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my foreach loop automatically jump to the third value in the collection?

I've come across something very peculiar, I'm utilizing resource files for string translation on a work project, and at the moment I have a piece of code which iterates through those resource files to find the localized versions of the Questions and Answers pertaining to a FAQ page, then loop through them and render them on a page.

The trouble is, one of my loops works perfect, but the other simply skips straight to Answer2!

My code is below, I really can't understand why 2 pieces of code exactly the same yield different results!

if (LanguageStrings.Culture == null)
{
    LanguageStrings.Culture = new CultureInfo("en-gb");
    LanguageStrings_FAQ.Culture = new CultureInfo("en-gb");
    LanguageStrings_FAQAnswers.Culture = new CultureInfo("en-gb");
}

CultureInfo ResxCulture = new CultureInfo(LanguageStrings.Culture.Name);
List<string> FAQQuestions = new List<string>();

ResourceSet RS = LanguageStrings_FAQ.ResourceManager.GetResourceSet(ResxCulture, true, true);

foreach (DictionaryEntry entry in RS)
{
    FAQQuestions.Add(entry.Value.ToString());
}

List<string> FAQAnswers = new List<string>();

ResourceSet RSAnswers = LanguageStrings_FAQAnswers.ResourceManager.GetResourceSet(ResxCulture, true, true);

foreach (DictionaryEntry entry in RSAnswers)
{
    FAQAnswers.Add(entry.Value.ToString());
}

The first item in RS is 0, which has a key of Questions0 as I'd expect, but in the second loop index 0 is Answers2!

Could anyone give me a pointer as to why this situation is occurring?

like image 601
Captain_Custard Avatar asked Jan 07 '23 08:01

Captain_Custard


1 Answers

You get the "wrong" element of the collection because ResourceSet is unordered:

The ResourceSet class enumerates over an IResourceReader, loading every name and value, and storing them in a Hashtable.

Whenever a HashTable is used, the order of iteration is unspecified. If you would like your resources to come in a specific order, you need to order them yourself, for example, by applying OrderBy by some property.

like image 116
Sergey Kalinichenko Avatar answered Jan 19 '23 17:01

Sergey Kalinichenko