SoFunction
Updated on 2025-03-01

DataTable query practical tutorial in C#

DataTable query

During my work, I encountered the need to conduct DataTable for querying. I briefly studied it and finally used the solution to implement it. It was simple to record it for easy use in the future.

DataTable dt = ();//Get all data of DataTable and prepare for queryDataRow[] dtRow = ("Adjustment date=‘"+()+"'");//Filter all columns that meet the conditions based on the query conditionsDataTable dtNew = ();//Clone a new table with the same structure as the original table (excluding data)foreach (DataRow item in dtRow)//Put all the competitions that meet the conditions into the new table{
  (item);
}
(dtNew);//Bind new values ​​to the control(That is, query results)

Supplement: C# query DataTable data through LINQ, and the result generates DataTable

I won't say much nonsense, let's just read the code~

var query = from g in dt_stu.AsEnumerable()
				  group g by new { 
					  t1 = <string>("STU_ID"), 
					  t2 = <string>("CLASS_ID")
				  } into m
			select new
			{
				STU_ID = .t1,
				CLASS_ID=.t2,
				Total results = (a => <decimal>("score")),
				Excellent number = (a => <decimal>("score")>95)
			};
DataTable dt_article = (query); 
 
/// <summary>
/// LINQ returns DataTable type/// </summary>
/// <typeparam name="T"> </typeparam>
/// <param name="varlist"> </param>
/// <returns> </returns>
public static DataTable ToDataTable<T>(IEnumerable<T> varlist)
{
	DataTable dtReturn = new DataTable();
 
	// column names
	PropertyInfo[] oProps = null;
 
	if (varlist == null)
		return dtReturn;
 
	foreach (T rec in varlist)
	{
		if (oProps == null)
		{
			oProps = ((Type)()).GetProperties();
			foreach (PropertyInfo pi in oProps)
			{
				Type colType = ;
 
				if (() && (()
				== typeof(Nullable<>)))
				{
					colType = ()[0];
				}
 
				(new DataColumn(, colType));
			}
		}
 
		DataRow dr = ();
 
		foreach (PropertyInfo pi in oProps)
		{
			dr[] = (rec, null) == null ?  : 
			(rec, null);
		}
 
		(dr);
	}
	return dtReturn;
}

The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.