Posted on 2007-09-03 13:54
玄铁剑 阅读(360)
评论(0) 编辑 收藏 引用 所属分类:
asp.net 、
C# Winform
public DataTable GetFuncDefine()
{
//distinct rows
DataTable dt = from database...
object[] fixColum = new object[] { "fixcol1", "fixcol1"};//fixcolumn can be set "";
object rowToColFeild = "rowcol";
object rowToColValue = "value";
return TranslateTable(fixColum, rowToColFeild, rowToColValue,typeof(DataType), dt);
}
static public DataTable TranslateTable(object[] fixColum, object rowToColFeild, object FeildValue, Type coltype, DataTable dt)
{
DataTable dtCross = new DataTable();
string strFixColum = "";
string strRowColum = "";
string strFull = "";
foreach (object obj in fixColum)
{
foreach (DataColumn col in dt.Columns)
{
if ((obj.ToString().ToLower() == col.ColumnName.ToString().ToLower())
&& (!strFull.Contains(obj.ToString().ToLower() + ",")))
{
strFixColum = strFixColum + obj.ToString().ToLower() + ",";
strFull = strFixColum;
dtCross.Columns.Add(col.ColumnName.ToString(), col.DataType);
break;
}
}
}
foreach (DataRow dr in dt.Rows)
{
foreach (DataColumn col in dt.Columns)
{
if ((rowToColFeild.ToString().ToLower() == col.ColumnName.ToString().ToLower())
&& (!strFull.Contains(dr[col].ToString().ToLower() + ",")))
{
strRowColum = strRowColum + dr[col].ToString().ToLower() + ",";
strFull = strFull + dr[col].ToString().ToLower() + ",";
dtCross.Columns.Add(dr[col].ToString(), coltype);
break;
}
}
}
//strFull = strFull.TrimEnd(",");
//object[] objFullColum = strFull.Split(new Char[] { ',' });
strFixColum = strFixColum.TrimEnd(',');
strRowColum = strRowColum.TrimEnd(',');
object[] objFixRC = strFixColum.Split(new Char[] { ',' });
object[] objRowColum = strRowColum.Split(new Char[] { ',' });
DataRow[] rowSelect;
DataRow NewRow;
DataTable dtClone = dt.Clone();
dtClone = dt.Copy();
string newfilter = "";
string oldfilter = "";
Boolean bRowExe = false;
foreach (DataRow dr in dt.Rows)
{
oldfilter = "";
foreach (object obj in fixColum)
{
if (obj.ToString().Equals("") == true)
continue;
oldfilter = oldfilter + obj.ToString() + "='" + dr[obj.ToString()].ToString() + "' And ";
}
if (oldfilter.Equals("") == false)
{
oldfilter = oldfilter.Trim().Substring(0, oldfilter.Trim().Length - 3);
}
else
{
oldfilter = "1=1";
}
if (oldfilter != newfilter)
{
bRowExe = false;
NewRow = dtCross.NewRow();
rowSelect = dtClone.Select(oldfilter);
foreach (DataRow rsdr in rowSelect)
{
if (bRowExe == false)
{
foreach (object obj in objFixRC)
{
if (obj.ToString().Equals("") == true)
continue;
NewRow[obj.ToString()] = rsdr[obj.ToString()];
}
bRowExe = true;
}
foreach (object obj in objRowColum)
{
if (rsdr[rowToColFeild.ToString()].ToString().ToLower() == obj.ToString().ToLower())
{
NewRow[obj.ToString()] = rsdr[FeildValue.ToString()];
break;
}
}
}
dtCross.Rows.Add(NewRow);
newfilter = oldfilter;
}
}
return dtCross;
}