繁体   English   中英

c#csv计算文件或datagridview中的指定数据

[英]c# csv count a specified data in file or in 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
     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);
            }

我找到了很多解决方案来计算第二列指定数据:111但是我遇到了问题。

         int xCount = dgv.Rows.Cast<DataGridViewRow>().Select(row => row.Cells["second col"].Value).Where(s => s !=null && Equals(111)).Count();

        this.lb_qty.Text = xCount.ToString();

但是它为row.Cells [“second col”]提供了错误。值

 An unhandled exception of type 'System.ArgumentException' occurred in System.Windows.Forms.dll

 Additional information: Column named second col cannot be found.

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

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

如果您仍想使用DataTable,请计算如下值:

int xCount = dgv_table.Rows.Cast<DataRow>().Count(r => r["second col"] != null && r["second col"].ToString() == "111");

我会尝试将文件读入DataTable并将其用作DataGridView DataSource

DataTable d_Table = new DataTable();

//fill the DataTable
this.dgv_table.DataSource = d_Table;

要计算第二列中包含111的行,您可以选择DataTable如下所示:

DataTable d_Table = new DataTable();

//fill the DataTable

DataRow[] rowCount = d_Table.Select("secondCol = '111'");
this.lb_qty.Text = rowCount.Length.ToString();

或者你可以在foreach -loop中做到这一点:

int count = 0;

foreach(DataGridViewRow dgr in this.dgv_table.Rows)
{
    if(dgr.Cells["secondCol"].Value.ToString() == "111") count++;
}
this.lb_qty.Text = count.ToString();
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;
}

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

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

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;
}

每个数组都代表一个列,因此您可以使用LINQ或甚至循环简单地找到任何值的频率:

foreach (var item in tmp[1].GroupBy(c => c))
                {
                    Console.WriteLine("{0} : {1}", item.Key, item.Count());
                }

暂无
暂无

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

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