C# c csv对文件或datagridview中的指定数据进行计数

C# c csv对文件或datagridview中的指定数据进行计数,c#,csv,datagridview,C#,Csv,Datagridview,我有一个csv文件,想数2。列多少次包含111 csv文件有46个带分隔符的分隔列 "first col" "second col" "....." abc 111 a abc 112 b abc 113 c abc 111 d abc 112 e

我有一个csv文件,想数2。列多少次包含111

csv文件有46个带分隔符的分隔列

    "first col"  "second col" "....."
     abc          111           a
     abc          112           b
     abc          113           c
     abc          111           d
     abc          112           e
     abc          113           f
我想数一数111。 首先填充datagridview fom数据表

        dgv.DataSource = dgv_table;

        string[] raw_text = File.ReadAllLines("d:\\"+lb_csv.Text);
        string[] data_col = null;
        int x = 0;

        foreach (string text_line in raw_text)
        {

            // MessageBox.Show(text_line);
            data_col = text_line.Split(';');

            if (x == 0)
            {
                for (int i = 0; i <= data_col.Count() - 1; i++)
                {

                    dgv_table.Columns.Add(data_col[i]);
                }
                //header

                x++;
            }

            else
            {
                //data

              dgv_table.Rows.Add(data_col);
            }

有人能帮我解决这个问题并获得所需的结果吗?

我会尝试将该文件读入数据表,并将其用作DataGridView的数据源

要对第二列中包含111的行进行计数,可以如下选择DataTable:

DataTable d_Table = new DataTable();

//fill the DataTable

DataRow[] rowCount = d_Table.Select("secondCol = '111'");
this.lb_qty.Text = rowCount.Length.ToString();
int xCount = dgv_table.Rows.Cast<DataRow>().Count(r => r["second col"] != null && r["second col"].ToString() == "111");
也可以在foreach循环中执行此操作:

编辑: StreamReader.ReadLine读取该行,但使用此方法,我们将跳转到第二行。如果没有更多的行,它将返回null,这就是我们的结束条件。我认为代码的其余部分是可读的 : 没有测试,所以要小心:
搜索时,在某些地方可能需要使用Trim或ToUpperCase。

我建议您跳过使用DataGridView,在循环中使用计数器变量,就像Arkadiusz建议的那样

如果仍要使用DataTable,请按如下方式计算值:

DataTable d_Table = new DataTable();

//fill the DataTable

DataRow[] rowCount = d_Table.Select("secondCol = '111'");
this.lb_qty.Text = rowCount.Length.ToString();
int xCount = dgv_table.Rows.Cast<DataRow>().Count(r => r["second col"] != null && r["second col"].ToString() == "111");

您可以使用此方法将CSV保存到阵列列表中

public static List<string[]> readCSV(String filename)
{
    List<string[]> result = new List<string[]>();
    try
    {
        string[] line = File.ReadAllLines(filename);
        foreach (string l in line)
        {
            string[] value= vrstica.Split(',');
            result.Add(value);
        }
    }
    catch (Exception e)
    {
        Console.WriteLine("Error: '{0}'", e);
    }
    return result;
}

我不确定您是如何避免dgv_table.Columns.Adddata_col[I]出现错误的;data_col应该是一个字符串[],并且对于只接受字符串的列没有Add方法。除非dgv_table是一个DataTable,这可能会很有用,因为知道它会很有用。@BlakeThingstad我尝试了DataGridView˛和DataTable,但仍然没有来自Zoltan的单词…:它返回:System.Core.dll中发生“System.InvalidCastException”类型的未处理异常。其他信息:无法将“System.Data.DataRow”类型的对象强制转换为“System.Windows.Forms.DataGridViewRow”类型。@Zoltan抱歉,您的问题很难理解。。。那么,您使用的是DataTable,而不是DataGridView?。。。在这种情况下,看看编辑的答案亲爱的尼诺,你是对的,我忘记了我从datatable填充到datagridviewDear Wudge的一个部分,它返回了无效的强制转换,但id i mod像这样,而我返回了空引用异常。。整数计数=0;foreach DataGridViewRow dgr在this.dgv.Rows{if dgr.Cells[1].Value.ToString==2581 count++;}this.lb_qty.Text=count.ToString;第二列中是否有空记录?如果是,您可以如下更改If:If dgr.Cells[1].Value!=null&&dgr.Cells[1]。Value.ToString==2581 count++;
int CountValues(string input, string searchedValue, int ColumnNumber, bool skipFirstLine = false)
{
                int numberOfSearchedValue= 0;
                string line;

            using (StreamReader reader = new StreamReader (input))
            {
                if(skipFirstLine)
                    reader.ReadLine();

                while ((line = reader.ReadLine()) != null)
                {
                    if(line.Split(';')[ColumnNumber] == searchedValue)
                       numberOfSearchedValue++;
                }
            }
      return numberOfSearchedValue;
}
int xCount = dgv_table.Rows.Cast<DataRow>().Count(r => r["second col"] != null && r["second col"].ToString() == "111");
public static List<string[]> readCSV(String filename)
{
    List<string[]> result = new List<string[]>();
    try
    {
        string[] line = File.ReadAllLines(filename);
        foreach (string l in line)
        {
            string[] value= vrstica.Split(',');
            result.Add(value);
        }
    }
    catch (Exception e)
    {
        Console.WriteLine("Error: '{0}'", e);
    }
    return result;
}
foreach (var item in tmp[1].GroupBy(c => c))
                {
                    Console.WriteLine("{0} : {1}", item.Key, item.Count());
                }