我们在做项目的时候,经常需要根据表或DataTable中某些字段来归类,为此就写出以下方法,帮组需要的人。
#region 对DataTable进行分组 + public void GroupDataRows(IEnumerable<DataRow> source, List<DataTable> destination, string[] groupByFields, int fieldIndex, DataTable schema) /// <summary> /// 对DataTable进行分组 /// </summary> /// <param name="source">要分组DataTable的Row集合</param> /// <param name="destination">分组之后的数据</param> /// <param name="groupByFields">分组字段</param> /// <param name="fieldIndex">字段索引(从什么字段开始)</param> /// <param name="schema">要分组DataTable</param> public void GroupDataRows(IEnumerable<DataRow> source, List<DataTable> destination, string[] groupByFields, int fieldIndex, DataTable schema) { if (fieldIndex >= groupByFields.Length || fieldIndex < 0) { DataTable dt = schema.Clone(); foreach (DataRow row in source) { DataRow dr = dt.NewRow(); dr.ItemArray = row.ItemArray; dt.Rows.Add(dr); } destination.Add(dt); return; } var results = source.GroupBy(o => o[groupByFields[fieldIndex]]); foreach (var rows in results) { GroupDataRows(rows, destination, groupByFields, fieldIndex + 1, schema); } fieldIndex++; } #endregion