繁体   English   中英

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

[英]How to count similar values in csv and import into asp.net (C#) gridview?

我有这样的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的所有数据

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
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();

暂无
暂无

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

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