C\#의 DataTable 실전 튜 토리 얼 조회

데이터 테이블 조회
업무 중 에 DataTable 을 조회 해 야 하 는 수 요 를 만 나 간단하게 연 구 했 고 최종 적 으로 방안 을 사용 하여 실현 했다.간단하게 기록 하면 나중에 사용 하기에 편리 하 다.

DataTable dt = dataBox.GetDataForDataTable();//  DataTable    ,      
DataRow[] dtRow = dt.Select("    =‘"+MediumCode.Text.Trim()+"'");//      ,           
DataTable dtNew = dt.Clone();//            (     )
foreach (DataRow item in dtRow)//              
{
  dtNew.ImportRow(item);
}
dataBox.DataBinding(dtNew);//       (     )
보충:C\#LINQ 를 통 해 DataTable 데 이 터 를 조회 한 결과 DataTable 이 생 성 되 었 습 니 다.
긴 말 안 할 게 요.그냥 코드 보 세 요~

var query = from g in dt_stu.AsEnumerable()
				  group g by new { 
					  t1 = g.Field<string>("STU_ID"), 
					  t2 = g.Field<string>("CLASS_ID")
				  } into m
			select new
			{
				STU_ID = m.Key.t1,
				CLASS_ID=m.Key.t2,
				      = m.Sum(a => a.Field<decimal>("  ")),
				     = m.Count(a => a.Field<decimal>("  ")>95)
			};
DataTable dt_article = UserClass.ToDataTable(query); 
 
/// <summary>
/// LINQ  DataTable  
/// </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)rec.GetType()).GetProperties();
			foreach (PropertyInfo pi in oProps)
			{
				Type colType = pi.PropertyType;
 
				if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition()
				== typeof(Nullable<>)))
				{
					colType = colType.GetGenericArguments()[0];
				}
 
				dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
			}
		}
 
		DataRow dr = dtReturn.NewRow();
 
		foreach (PropertyInfo pi in oProps)
		{
			dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue
			(rec, null);
		}
 
		dtReturn.Rows.Add(dr);
	}
	return dtReturn;
}
이상 은 개인 적 인 경험 이 므 로 여러분 에 게 참고 가 되 기 를 바 랍 니 다.여러분 들 도 저 희 를 많이 응원 해 주시 기 바 랍 니 다.만약 잘못 이 있 거나 완전히 고려 하지 않 은 부분 이 있다 면 아낌없이 가르침 을 주시 기 바 랍 니 다.

좋은 웹페이지 즐겨찾기