【问题标题】:What is best way of filter datatable?过滤数据表的最佳方法是什么?
【发布时间】:2012-01-26 16:45:04
【问题描述】:

在我的一个 c# 要求中,我有一个数据表,其中我有以下数据

Category Topics Resourceworked 
A        tp1    Hemant
A        tp2    Kevin
B        tp3    Haris
B        tp4    Hemant
B        tp5    Hemant
C        tp6    Kevin

在输出中我想要两组数据

OutPut-1:对于每个独特的类别,有多少资源工作

Category  NoOfResorces
A         2
B         2
C         1

输出 2:资源为 unquie 类别工作了多少次,例如

Category  Resource   NoOfTime
A         Hemant     1
A         Kevin      1
B         Haris      1
B         Hemant     2
C         Kevin      1

实现输出的最佳方法是什么,即数据表过滤器或 LINQ?

补充: 任何 LINQ 专家都可以告诉我学习 LINQ 的好在线网站或书籍吗?

【问题讨论】:

    标签: c# linq datatable


    【解决方案1】:

    这是您的第一个要求:

    var uniqueCat = from d in tblData.AsEnumerable()
                    group d by (string)d["Category"] into Group
                    select Group;
    var catRes = from grp in uniqueCat
                 let c = grp.Select(r => r["Resourceworked"]).Distinct().Count()
                 select new {Category = grp.Key, NoOfResorces=c};
    
    var summary = from cr in catRes
             select string.Format("Category:{0} Count:{1}",cr.Category,cr.NoOfResorces);
    MessageBox.Show(string.Join(Environment.NewLine,summary));
    

    这是第二个查询:

    var uniqueCatRes = from d in tblData.AsEnumerable()
                       group d by new{Cat= d["Category"], Res=d["Resourceworked"]} into Group 
                       select Group;
    var catResCount = from grp in uniqueCatRes
                      let Category = grp.Key.Cat
                      let Resource = grp.Key.Res
                      let NoOfResorces = grp.Count()
                      select new { Category,Resource,NoOfResorces };
    
    summary = from crc in catResCount
              select string.Format("Category:{0} Resource:{1} Count:{2}", crc.Category,crc.Resource, crc.NoOfResorces);
    MessageBox.Show(string.Join(Environment.NewLine,summary));
    

    【讨论】:

    • 可以把SUMMARY转成DataTable吗?我遇到了一些类型转换错误。
    猜你喜欢
    • 1970-01-01
    • 2011-01-20
    • 2012-05-26
    • 2010-10-07
    • 1970-01-01
    • 2019-10-26
    • 1970-01-01
    • 2019-10-30
    • 2015-02-27
    相关资源
    最近更新 更多