如何计算csv中的相似值并导入到asp.net(C#)gridview中?

时间:2013-11-21 20:28:59

标签: c# asp.net csv

我有这样的CSV(使用管道分隔符)

a|45
b|45
c|55
d|65
e|45

我想要做的是在gridview中显示,条目数量,如

45-3
55-1
65-1

我怎样才能实现这个目标?

我现在正在这样做

//  get all lines of csv file
    string[] str = File.ReadAllLines(Server.MapPath("Test.csv"));

    // create new datatable
    DataTable dt = new DataTable();

    // get the column header means first line
    string[] temp = str[0].Split('|');

    // creates columns of gridview as per the header name
    foreach (string t in temp)
    {
        dt.Columns.Add(t, typeof(string));
    }

    // now retrive the record from second line and add it to datatable
    for (int i = 1; i < str.Length; i++)
    {
        string[] t = str[i].Split('|');
        dt.Rows.Add(t);

    }

    // assign gridview datasource property by datatable
    GridView1.DataSource = dt;

    // bind the gridview
    GridView1.DataBind();

它现在打印出来自csv的所有数据

2 个答案:

答案 0 :(得分:3)

var data = File.ReadAllLines(Server.MapPath("Test.csv"))
               .Select(s => s.Split('|')[1].Trim())
               .GroupBy(s => s)
               .Select(s => new 
                {
                    Value = s.Key,
                    Count = s.Count()
                })
               .ToList();
GridView1.DataSource = data;
GridView1.DataBind();

会得到你:

Value   Count
 45       3
 55       1
 65       1

答案 1 :(得分:0)

GridView1.DataSource = File.ReadAllLines(Server.MapPath("Test.csv")).GroupBy(line => new { l = line.Split('|')[1] }).Select(a => new { text = a.Key.l + "-" + a.Count() }).ToArray();