This method should be written to a project recently. Based on a datatable. If one of its columns is Int or float. The combination is required.
Write down below,
Code
Datatable table = new datatable ();
Table. Columns. Add ("intcolumn", typeof (INT ));
Table. Columns. Add ("stringcolumn", typeof (string ));
Table. Columns. Add ("datetimecolumn", typeof (datetime ));
Table. Rows. Add (1, "Row 1st", datetime. Now );
Table. Rows. Add (2, "row 2nd", datetime. Now );
Table. Rows. Add (3, "Row 3rd", datetime. Now );
Table. Rows. Add (4, "Row 4th", datetime. Now );
Table. Rows. Add (5, "Row 5th", datetime. Now );
Table. Rows. Add (6, "Row 6th", datetime. Now );
Dictionary <string, string> numericcolumns = new dictionary <string, string> ();
Foreach (datacolumn column in table. columns)
{
If (column. datatype = typeof (INT ))
{
String sumname = string. Format ("sum ({0})", column. columnname );
Numericcolumns. Add (sumname, String. Format ("sum ({0})", column. columnname ));
}
}
Foreach (string key in numericcolumns. Keys)
{
Table. Columns. Add (Key, typeof (INT), numericcolumns [Key]);
}
Table. acceptchanges ();
// Print table
Foreach (datarow row in table. Rows)
{
Foreach (datacolumn column in table. columns)
{
Console. Write ("{0}", row [column]);
}
Console. Write ("\ r \ n ");
}
Result
1 1st rows 2009/11/23 10:49:27 21
2. row 2nd, 2009/11/23 10:49:27, 21
3. row 21, 2009/11/23 10:49:27, 21
4. row 21, 2009/11/23 10:49:27, 21
5. row 21, 2009/11/23 10:49:27, 21
6. row 21, 2009/11/23 10:49:27, 21
When writing a datatable today. I did not expect to use LINQ.
The following figure shows LINQ Able's LINQ alization.
Code
Ienumerable <datarow> rows = DT. Rows. oftype <datarow> ();
Rows. groupby (A => A ["A"]. tostring (). Select (A => New
{
A = A. First () ["A"]. tostring (),
Percent = A. Count ()/dt. Rows. Count
});
VaR query = From DT in dv1.table. asenumerable ()
Group DT by DT. Field <string> ("category ");
Foreach (var dd in query)
{
Combox1.items. Add (DD. Key );
}