Search code examples
c#loopspositionstartswith

Getting index position of string in List C#


Trying to get the index position of a string in a List but it keeps returning zero(0) as the index integer variable.

Any ideas what is wrong? I have tried changing to public int and so on.

        public int GetLangPos(string cultureCode)
    {


        CsvRead csvRead = new CsvRead();


        int index = 0;
        foreach (string line in csvRead.headerNames)
        {
            if (line.StartsWith(cultureCode)) { return index; }
            index++;
        }
        return index;
    }

CsvRead class:

class CsvRead
{

    public List<CsvLine> _csvLines = new List<CsvLine>(); //stores the csv lines
    public List<string> headerNames = new List<string>(); //stores the headers of the csv file

    public void GetValue()
    {

        /*
        Key|Name|es-ES|fr-FR|ru-RU
        web_key_001|Message|Mensaje|Message|Сообщение //row0
        web_key_002|Close|Cerca|Fermer|Закрыть //row1
        web_key_003|Administration|Administración|Administration|Aдминистрация //row2
        web_key_004|Confirm|Confirmar|Confirmer|подтвердить //row3
        web_key_005|Success|Éxito|Succès|Yспех //row4
        */

        FileStream f = new FileStream(ConfigurationManager.AppSettings["TranslationsCsv"], FileMode.Open);
        StreamReader streamReader = new StreamReader(f);
        CsvConfiguration config = new CsvConfiguration();
        config.Delimiter = "|";
        CsvReader csvReader = new CsvReader(streamReader, config);


        using (csvReader)
        {
            while (csvReader.Read())
            {
                headerNames = csvReader.FieldHeaders.ToList<string>();



                CsvLine csvLine = new CsvLine();

                for (int i = 0; i < headerNames.Count(); i++)
                {
                    csvLine.fieldValues.Add(csvReader.GetField<string>(headerNames.ElementAt(i)));
                }

                _csvLines.Add(csvLine);


            }


            //test section start



            //test section end

        }
    }
}

Solution

  • The issue seems to be a misunderstanding in how object instances work.

    When you create an instance of a class using the new operator, you create a new instance of that object. The values of that object's instance fields (those without the static modifier) will belong to that instance only.

    If you've called GetValue on some instance in Main, as you suggest, then the 'new' instance you create at GetLangPos will not share any of the state of this other instance.

    As you've already read the file, you should probably re-use the results of that by re-using that instance rather than creating a new one in GetLangPos and reading the file again.