如何从datatable获取相同数据类型的列的列表 [英] How to get the list of columns of same datatype from datatable
本文介绍了如何从datatable获取相同数据类型的列的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的程序中有一个数据表,我想得到具有相同数据类型的列的列表。
i使用以下代码:
DataTable dt = new DataTable();
dt.Columns.Add( col1, typeof ( string ));
dt.Columns.Add( col2, typeof ( string ));
dt.Columns.Add( col3, typeof ( int ));
dt.Columns.Add( col4, typeof ( string ));
列表< DataColumn> string_type_columns = new 列表< DataColumn>();
for ( int i = 0 ; i < dt.Columns.Count; i ++)
{
if (dt.Columns [i] .DataType.ToString()。Equals( System.String))
{
string_type_columns.Add(dt.Columns [i]);
}
}
string_type_columns将为我提供具有字符串数据类型的列的列表。
但是在我的实际程序中,我的表中可以有超过40列,所以我不想遍历每一列数据表。
有没有其他(更好)的方法呢?
解决方案
这里是解决方案使用较少的代码
var string_type_columns = dt.Columns.Cast< ; DataColumn>()。其中(c = > c.DataType == typeof (字符串跨度>));
i am having a datatable in my program, i want to get the list of the columns which has same data type.
i used the following code:
DataTable dt = new DataTable();
dt.Columns.Add("col1", typeof(string));
dt.Columns.Add("col2", typeof(string));
dt.Columns.Add("col3", typeof(int));
dt.Columns.Add("col4", typeof(string));
List<DataColumn> string_type_columns = new List<DataColumn>();
for (int i = 0; i < dt.Columns.Count;i++ )
{
if (dt.Columns[i].DataType.ToString().Equals("System.String"))
{
string_type_columns.Add(dt.Columns[i]);
}
}
string_type_columns will give me the list of the columns which has string datatype.
but in my actual program there can be more than 40 columns in my table so i don't want to loop through each column of datatable.
is there any other (better) way to do this?
解决方案
here is the solution which uses the less code
var string_type_columns = dt.Columns.Cast<DataColumn>().Where(c => c.DataType == typeof(String));
这篇关于如何从datatable获取相同数据类型的列的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文