导航

linq to datatable group by 多列 实现

Posted on 2011-12-22 16:18  毅无涯  阅读(2475)  评论(0编辑  收藏  举报

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
  */
}