和http://social.msdn.microsoft.com/Forums/zh-CN/1b0aafdd-2e51-46d5-8e25-87d4866ff4b6/datatable
大部分都是抄的!!
有写时候,我们已经从数据层得到了一个datatable,现在我们需要对某几列进行分组,比如对下面学生按照年龄和性别分组:
姓名 年龄 性别 学校
小明 12 男 光明小学
小红 12 女 光明小学
小米 12 男 黑暗小学
================================================小明 12 男 光明小学
小米 12 男 黑暗小学
小红 12 女 光明小学
class Program
{
static void Main(string[] args)
{
string connection = "*********** ";
SqlConnection cn = new SqlConnection(connection);
cn.Open();
string selectCmd = "***************";
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(selectCmd, cn);
adapter.Fill(ds, "*****");
DataTable mytb = ds.Tables["***"];
List<DataTable> groupsTb = DataTableGroups(new string[] { "你想要的列名", "*****" }, mytb);
Console.Read();
}//end main
public static 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++;
}
public static List<DataTable> DataTableGroups(string[] fields, DataTable source)
{
List<DataTable> dts = new List<DataTable>();
GroupDataRows(source.Rows.Cast<DataRow>(),dts,fields,0, source);
return dts;
}
}//end class