如何将数据表的列转换为列表
本文关键字:转换 列表 数据表 | 更新日期: 2023-09-27 18:01:35
我有一个多列的DataTable。我想从DataTable的第一列中得到一个List<String>
。我该怎么做呢?
试试这个:
static void Main(string[] args)
{
var dt = new DataTable
{
Columns = { { "Lastname",typeof(string) }, { "Firstname",typeof(string) } }
};
dt.Rows.Add("Lennon", "John");
dt.Rows.Add("McCartney", "Paul");
dt.Rows.Add("Harrison", "George");
dt.Rows.Add("Starr", "Ringo");
List<string> s = dt.AsEnumerable().Select(x => x[0].ToString()).ToList();
foreach(string e in s)
Console.WriteLine(e);
Console.ReadLine();
}
var list = dataTable.Rows.OfType<DataRow>()
.Select(dr => dr.Field<string>(columnName)).ToList();
[Edit:添加System.Data.DataSetExtensions
的引用到您的项目,如果这不能编译]
给你
DataTable defaultDataTable = defaultDataSet.Tables[0];
var list = (from x in defaultDataTable.AsEnumerable()
where x.Field<string>("column1") == something
select x.Field<string>("column2")).ToList();
如果需要第一列
var list = (from x in defaultDataTable.AsEnumerable()
where x.Field<string>(1) == something
select x.Field<string>(1)).ToList();
这是你需要的吗?
DataTable myDataTable = new DataTable();
List<int> myList = new List<int>();
foreach (DataRow row in myDataTable.Rows)
{
myList.Add((int)row[0]);
}
我就像下面这样做,当你把你的列设置为可枚举的,你可以排序,排序或你想要的。
_dataTable.AsEnumerable().Select(p => p.Field<string>("ColumnName")).ToList();
我给你做了一个样品,希望对你有帮助。
static void Main(string[] args)
{
var cols = new string[] { "col1", "col2", "col3", "col4", "col5" };
DataTable table = new DataTable();
foreach (var col in cols)
table.Columns.Add(col);
table.Rows.Add(new object[] { "1", "2", "3", "4", "5" });
table.Rows.Add(new object[] { "1", "2", "3", "4", "5" });
table.Rows.Add(new object[] { "1", "2", "3", "4", "5" });
table.Rows.Add(new object[] { "1", "2", "3", "4", "5" });
table.Rows.Add(new object[] { "1", "2", "3", "4", "5" });
foreach (var col in cols)
{
var results = from p in table.AsEnumerable()
select p[col];
Console.WriteLine("*************************");
foreach (var result in results)
{
Console.WriteLine(result);
}
}
Console.ReadLine();
}
1。非常简单的代码迭代数据表和获取列列表。
2。代码==>>>
foreach (DataColumn dataColumn in dataTable.Columns)
{
var list = dataTable.Rows.OfType<DataRow>()
.Select(dataRow => dataRow.Field<string>
(dataColumn.ToString())).ToList();
}