如何将列表转换为数据表C# [英] How to convert list to datatable C#
本文介绍了如何将列表转换为数据表C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须循环进入页面并从html表中获取数据,每次循环并获取它们进入列表时,我都将获取列表中的所有数据.如何将它们传递到数据表中,其中列表中的所有行只有一个列和值不同??我尝试将它们转换为字典并将其传递到数据表,但是我得到了重复列的错误?这是我的代码
我尝试过的事情:
i have to loop in page and get data from html table i get all the data in a list each time i loop and get them into list how can i pass them to data table where all the rows of the list has only one column and different in values ?? i try to convert them to dictionary and pass them to data table but i have get error duplicate column ?? this is my code
What I have tried:
List<string> list = new List<string>();
if (pagevalue != null)
{
foreach (HtmlNode data in pagevalue.DocumentNode.SelectNodes("//div"))
{
list.Add(infodata.InnerText);
}
if (list.Count > 0)
{
var dict = list.ToDictionary(k => k, v => v);
foreach (KeyValuePair<string, string> item in dict)
{
DataRow dataRow = dt.NewRow();
dt.Columns.Add(item.Key);
}
DataSet ds = new DataSet();
ds.Tables.Add(dt);
}
推荐答案
为什么需要字典?试试这个并适应:
Why do you need dictionary? Try this and adapt:
List<string> cities = new List<string>();
cities.Add("New York");
cities.Add("Mumbai");
DataTable table = new DataTable();
table.Columns.Add("column1", typeof (string));
foreach (string str in cities)
{
DataRow row = table.NewRow();
row["column1"] = str;
table.Rows.Add(row);
}
这篇关于如何将列表转换为数据表C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文