• linq to datatable group by 多列 实现


    void Main()
    {
    DataTable dt=new DataTable();
    dt.Columns.Add("flightno");
    dt.Columns.Add("flightTime",typeof(DateTime));
    dt.Columns.Add("arrivalTime",typeof(DateTime));
    dt.Columns.Add("passenger");
    dt.Rows.Add("AU123",Convert.ToDateTime("2010-12-20 12:30"),Convert.ToDateTime("2010-12-20 15:30"),"小Q");
    dt.Rows.Add("AU123",Convert.ToDateTime("2010-12-20 12:30"),Convert.ToDateTime("2010-12-20 15:30"),"小T");
    dt.Rows.Add("AU123",Convert.ToDateTime("2010-10-21 12:00"),Convert.ToDateTime("2010-12-21 14:30"),"小N");
    dt.Rows.Add("AU124",Convert.ToDateTime("2010-10-22 12:00"),Convert.ToDateTime("2010-12-22 11:30"),"小F");
    var query=from t in dt.AsEnumerable()
              group t by  new{t1=t.Field<DateTime>("flightTime"),t2=t.Field<DateTime>("arrivalTime")} into m
              select new
              {
              flightno=m.First().Field<string>("flightno"),
              flightTime=m.Key.t1,
              arrivalTime=m.Key.t2,
              passenger=string.Join("/",m.Select(n=>n.Field<string>("passenger")).ToArray()),
              rowcount=m.Count()
              };
      Console.WriteLine("==============输出结果:================");
      Console.WriteLine("flightno     flightTime               arrivalTime              passenger      rowcount" +"/n");
      query.ToList().ForEach(q=>Console.WriteLine(q.flightno+"    "+q.flightTime.ToString("yyyy-MM-dd HH:mm")+"     "+q.arrivalTime.ToString("yyyy-MM-dd HH:mm")+"    "+q.passenger+"                 "+q.rowcount));
      /*
      ==============输出结果:================
    flightno     flightTime               arrivalTime      passenger      rowcount
    AU123    2010-12-20 12:30     2010-12-20 15:30    小Q/小T             2
    AU123    2010-10-21 12:00     2010-12-21 14:30    小N                 1
    AU124    2010-10-22 12:00     2010-12-22 11:30    小F                 1
      */
    }

    E-MAIL:yiwuya@hotmail.com
    MSN:yiwuya@hotmail.com
    QQ:304899972
    纺织软件
  • 相关阅读:
    const与readonly
    JQuery Tooltipster
    Log4Net使用
    asp.net mvc 4 beta 版已发布
    控件属性
    C# 获取当前路径
    对toLocaleString()、toString()、valueOf()的理解
    靶场练习3CSRF攻击
    计算字符串长度
    Android ListView 自定义适配器
  • 原文地址:https://www.cnblogs.com/yiwuya/p/3018807.html
Copyright © 2020-2023  润新知