c# 获取数组索引 ID

本文关键字:ID 索引 数组 获取 | 更新日期: 2023-09-27 18:32:52

不确定我是否在正确的轨道上,但我想找到一个数组的索引 ID 并检查它是否等于另一个 id,然后显示一条消息。 由于某种原因,它不起作用。

int  _findID = 1;       
using (StreamReader reader = new StreamReader("textfile.txt"))
    {
    string line = reader.ReadLine();
    while (line != null)
    {
        string[] array = {line};
        for (int i = 0; i < array.Length; i++)
        {
            if (array[i] == findID)
            {
                MesssageBox.show("Line found!!")
            }
        }
    }
}

任何帮助表示赞赏

c# 获取数组索引 ID

试试

if(int.Parse(array[i]) == findID)

而不是

if (array[i] == findID)

您必须将数字的string表示转换为int,然后比较两个int

这甚至比迭代始终具有 1 个元素的数组还要短:

while (line != null) {
    if(int.Parse(array[i]) == findID)
        MesssageBox.Show("Line found!!")
}

编辑

尝试

int  _findID = 1;
List<String> names = new List<string>()
using (StreamReader reader = new StreamReader("textfile.txt"))
{
    string line = reader.ReadLine();
    int lineCount = 0;
    while (line != null)
    {
        lineCount++;
        names.Add(line);
        if (lineCount == _findID)
            MessageBox.Show("Line found!!");           
    }
}

@user1285872:数组。长度 当您检查 (array[i] == findID) 时,这将给出数组长度 1 如果 findID = =0 的值将显示 (0==findID),则会显示消息。

您的代码存在各种问题:

首先,如果文件不为空,则在读取该行一次并始终检查同一行时,您将有一个无限循环:

string line = reader.ReadLine();
while (line != null) {}

数组始终为 1 个项目,只要您在循环本身中创建它。

但是对于lineID的问题,这样一行的内容到底是什么?