简体   繁体   English

从csv文件中提取特定列

[英]Extracting a specific column from a csv file

When I run this code it takes 11 elements in the first iteration. 当我运行此代码时,它在第一次迭代中需要11个元素。 In the second iteration it's reduced to 6 elements and in the last it takes 1 element and then shows an "array out of range exception". 在第二个迭代中,它减少到6个元素,在最后一个迭代中,它减少了1个元素,然后显示“数组超出范围异常”。

What am I doing wrong? 我究竟做错了什么?

foreach (string line in File.ReadLines(Path))
{  
    string [] column = line.Split(',');
    if (id == column[4])
    {
        return false;
    }
    Array.Clear(column, 0, column.Length);
}

If you say line has only 1 element on the 3rd iteration, then you make column = line.Split(','), column will have 1 element. 如果您说line在第三次迭代中只有1个元素,则使column = line.Split(','),column将有1个元素。 so at that point column[4] is "out of range" as the string array only has one element in it. 因此,此时column [4]处于“超出范围”,因为字符串数组中仅包含一个元素。

What exactly are you trying to do with this though, so we can give you an answer better than just the exception. 不过,您到底要尝试做什么呢,所以我们可以给您比仅是例外更好的答案。

edit: So by your comment all you have to do is see if the 5th column matches what's in id and return false if so? 编辑:因此,根据您的评论,您所要做的就是查看第5列是否匹配id中的内容,如果匹配则返回false?

foreach (string line in File.ReadLines(Path))
{  
    string [] column = line.Split(',');
    if (column.Count() >= 5 && column.id == column[4])
    {
        return false;
    }
}

this will ensure you have at least 5 elements in your column array before you try to access the 5th element column[4] in the == check. 这样可以确保在尝试访问==检查中的第5个元素column [4]之前,您的列数组中至少有5个元素。

Have you tried making sure that the row being check has enough columns ? 您是否尝试过确保要检查的行有足够的列?

By 4th column you mean the column at index 4 ? 第四列是指索引4处的列? or you mean the 4th column which is at index 3 ? 或者您是指索引3的第4列?

private bool SomeMethod(String path, String id)
{
    string [] column ;

    foreach (string line in File.ReadLines(Path))
    {  
        column = line.Split(',');

        //check that there are at least 5 columns before comparing it with ID
        if ((column.Length >= 5) && (id == column[4]))
        {
            return false;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM