获取List C#中字符串的索引位置

Getting index position of string in List C#

试图获取列表中字符串的索引位置,但它一直返回零 (0) 作为索引整数变量。

有什么问题吗?我试过改成 public int 等等。

        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

        }
    }
}

有两个可能的原因:

  1. 您没有填写 headerNames
  2. 您没有创建或初始化 headerNames 列表

请post检查 CsvRead 内部的所有代码

----编辑----

你必须坐这条线:

headerNames = csvReader.FieldHeaders.ToList<string>();

在 while 循环之外,即在所有迭代中读取 headers 并且文件末尾的行为空。

csvReader.Read(); // read the headers
headerNames = csvReader.FieldHeaders.ToList<string>();
while (csvReader.Read())
{
...
}

这个问题似乎是对对象实例工作方式的误解。

当您使用 new 运算符创建 class 的实例时,您会创建该对象的一个​​新实例。该对象的实例字段(没有 static 修饰符的那些)的值将属于 仅该实例 .

如果您按照您的建议在 Main 中的某个实例上调用了 GetValue,那么您在 GetLangPos 中创建的 'new' 实例将不会共享任何另一个实例的状态。

由于您已经阅读了该文件,您可能应该通过重新使用该实例来重新使用该文件的结果,而不是在 GetLangPos 中创建一个新实例并再次读取该文件。