Linq 是不是可以实现这样的功能?
DataTable dt = new DataTable();
da.Fill(dt);  假设数据已装载进入内存,dt表中有一个字段 EmployeeCode ,
想在内存的 dt 中实现如下的SQL 语句的功能:
select
EmployeeCode,
count(EmployeeCode) [nn]
from employeeMsg
group by EmployeeCode
having count(EmployeeCode) > 1
是不是 Linq 可以做到?
貌似这样,但语法有错呀。
请高手指点。var q =
    from p in dt.AsDataView()
    group p by p.EmployeeCode into g
    select new
    {
        g.EmployeeCode,
        Num = g.Count()
    };

解决方案 »

  1.   

    var q =
        from p in dt.Rows
        group p by p["EmployeeCode"].ToString() into g
        select new
        {
            Code = g.Key,
            Num = g.Count()
        };
      

  2.   

    回楼上:dt.Rows 提示错误:Error 1 Could not find an implementation of the query pattern for source type 'System.Data.DataRowCollection'.  'GroupBy' not found.  Consider explicitly specifying the type of the range variable 'p'. E:\Framework\HR.GrandTai\frmRequestHours.cs 158 31 HR.GrandTai
      

  3.   

    还要怎么加上这句:
     having count(EmployeeCode) > 1也就是只想查出 有2个及以上相同的工号。
      

  4.   

    var q =
        from p in dt.Rows.Cast<DataRow>()
        group p by p["EmployeeCode"].ToString() into g
        select new
        {
            Code = g.Key,
            Num = g.Count()
        };
      

  5.   

    var q =
        (from p in dt.Rows.Cast<DataRow>()
        group p by p["EmployeeCode"].ToString() into g
        select new
        {
            Code = g.Key,
            Num = g.Count()
        }).Where(x => x.Num > 1);
      

  6.   


    var q =from p in dt.AsEnumerable()
                   where p.Field<int>("EmployeeCode").Count()>1
                    select new
                     {
                              EmployeeCode = p.Field<string>("EmployeeCode"),
                             CountNumber =  p.Field<int>("EmployeeCode").Count()
                     };
      

  7.   

    #5楼的可以了。谢谢再请教一下:if ( q.个数 > 0 )  //我想在这里判断一下 q 集合的个数,这里怎么写?
    {
    foreach (var item in q)
    {
    MessageBox.Show(string.Format( "工号:{0},人数:{1}" ,item.Code,item.Num) );  
    }
       //其他代码.}
      

  8.   

    什么意思?if (q.Count() > 0)
    ...
      

  9.   

    还有个分组的:var q = from p in dt.AsEnumerable()
                   group p by p.Field<string>("EmployeeCode")
                    where p.Field<string>("EmployeeCode").Count()>1
                     select new 
                    { 
                         EmployeeCode = p.Field<string>("EmployeeCode"),
                         CountNumber = p.Field<string>("EmployeeCode").Count()
                     }; 
      

  10.   

    可以了,
    谢谢 caozhy结帐
      

  11.   

    可以写得更清晰一点var query = from DataRow r in dt.Rows
                let employee = (string)r["EmployeeCode"]
                group r by employee into g
                where g.Count() > 1
                select new { EmployeeCode = g.Key, Count = g.Count() };