简体   繁体   English

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

[英]c# csv count a specified data in file or in datagridview

I have a csv file and would like to count the 2. column how many times contains 111. 我有一个csv文件,想要计算2.列多少次包含111。

the csv file has 46 separated columns with separator ; csv文件有46个分隔列和分隔符; .

    "first col"  "second col" "....."
     abc          111           a
     abc          112           b
     abc          113           c
     abc          111           d
     abc          112           e
     abc          113           f

i would like to count the 111. Filled up first the datagridview fom datatable. 我想数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);
            }

I find a lots of solution to count the 2nd columns specified data:111 but all time i had problems. 我找到了很多解决方案来计算第二列指定数据: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();

But it gives error for row.Cells["second col"].Value 但是它为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.

Can someone help me how to solve this problem and get the needed result? 有人可以帮我解决这个问题,并获得所需的结果吗?

I would suggest you to skip using DataGridView and use counter variable in your loop, like Arkadiusz suggested. 我建议你跳过使用DataGridView并在循环中使用计数器变量,就像Arkadiusz建议的那样。

If you still want to work with DataTable, count values like this: 如果您仍想使用DataTable,请计算如下值:

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

I would try to read the file into a DataTable and use it as DataSource for the DataGridView . 我会尝试将文件读入DataTable并将其用作DataGridView DataSource

DataTable d_Table = new DataTable();

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

To count the rows wich contains 111 in the second column, you can select the DataTable like this: 要计算第二列中包含111的行,您可以选择DataTable如下所示:

DataTable d_Table = new DataTable();

//fill the DataTable

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

Or you can do it in a foreach -loop: 或者你可以在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;
}

Edit: StreamReader.ReadLine() reads the line but also, using this method we are jumping to second line. 编辑:StreamReader.ReadLine()读取行但是,使用此方法我们跳到第二行。 If there is no more lines it returns null, so that is our ending condition. 如果没有更多的行返回null,那么这就是我们的结束条件。 Rest of the code is readable, I think :) 其余的代码是可读的,我认为:)
Didn't test that so be careful :) 没测试那么小心:)
It might be necessary to use Trim() or ToUpperCase() in some places (as usually when you are searching). 可能需要在某些地方使用Trim()或ToUpperCase()(通常在搜索时)。

you can use this method to save the CSV into List of arrays List 您可以使用此方法将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;
}

every array will represent a column, so you can simply find the frequency of any value using LINQ or even loop: 每个数组都代表一个列,因此您可以使用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