我希望在C#中使用datatable获取表的任何列的最大大小。例如,如果我在数据库中有一个名为dept的表,其属性是NAME和ADDRESS,并且我将NAME的大小设置为varchar(50),将Address设置为varchar(30)。
现在我想得到50和30 .....
我写了这段代码
DataSet ds1 = new DataSet();
DataSet ds = new DataSet();
string query = Form1.query1Pass;
SqlCommand cmd = new SqlCommand(query.ToString(), con);
this.tablename1 = query.Substring(query.LastIndexOf("from")+4); ;
cmd.ExecuteNonQuery();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(this.ds);
string query2 = Form1.query2Pass;
cmd = new SqlCommand(query2, con);
adp = new SqlDataAdapter(cmd);
adp.Fill(this.ds1);
StringBuilder datatype2 = new StringBuilder();
this.datatype2.Append("Data Type Conflict: ");
this.datetimeCon.Append("DateTime Format Conflict: ");
DataTable table1 = this.ds.Tables[0];
DataTable table2 = this.ds1.Tables[0]; ;
DataColumnCollection col1 = table1.Columns;
DataColumnCollection col2 = table2.Columns;
foreach (DataColumn ds in col1) {
foreach (DataColumn ds2 in col2) {
if (ds.ColumnName.Equals(ds2.ColumnName)) {
if (!ds.DataType.Equals(ds2.DataType)) {
this.datatype2.Append(ds.ColumnName + "<" + ds.DataType + ">, " + ds2.ColumnName + "<" + ds2.DataType + ">,");
}
else
if (ds.MaxLength!=ds2.MaxLength) {
maxLength.Append(ds.ColumnName+"<"+ds.MaxLength+">, "+ds2.ColumnName+"<"+ds2.MaxLength+">,");
}
}
}
}
答案 0 :(得分:1)
我假设列不是Text
列。 MaxLength
property仅在DataType=String
的列上设置。 MSDN:
非文本列会忽略
MaxLength
属性。一个 如果您将ArgumentException
分配给a,则会引发MaxLength
异常 非 -string
列。
顺便说一句,您可能想要使用LINQ方法,但这是一个品味问题:
var t1Cols = table1.Columns.Cast<DataColumn>();
var t2Cols = table2.Columns.Cast<DataColumn>();
var diffTypes =
from t1Col in t1Cols
join t2Col in t2Cols on t1Col.ColumnName equals t2Col.ColumnName
where t1Col.DataType != t2Col.DataType
select string.Format("{0}<{1}>,{2}<{3}>",
t1Col.ColumnName, t1Col.DataType, t2Col.ColumnName, t2Col.DataType);
var diffMaxLength =
from t1Col in t1Cols
join t2Col in t2Cols on t1Col.ColumnName equals t2Col.ColumnName
where t1Col.MaxLength != t2Col.MaxLength
select string.Format("{0}<{1}>,{2}<{3}>",
t1Col.ColumnName, t1Col.MaxLength, t2Col.ColumnName, t2Col.MaxLength);
Console.WriteLine("diff. Types: " + string.Join(", ", diffTypes));
Console.WriteLine("diff. max Length: " + string.Join(", ", diffMaxLength));