如何使用扩展方法将列表转换为数据表 [英] How to convert list to datatable using extension method

查看:68
本文介绍了如何使用扩展方法将列表转换为数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题



将列表转换为数据表时的错误计数参数



我的列表如下

我的项目代码列表输出如下1830,950,902,540



如何转换列表字符串到数据表



我尝试过:



Problem

error mismatch count parameter when convert list to datatable

my list as below
my list output of itemcode as below "1830","950","902","540"

How to convert list of string to datatable

What I have tried:

static List<string> SimilarItems = new List<string>();
Similar = ConvertToString(dt.Rows[i]["ItemCode"]);
                    SimilarItems.Add(Similar);
dtcollectlistdata = Extensions.ToDataTable(SimilarItems);

public static DataTable ToDataTable<T>(List<T> items)
    {

        DataTable dataTable = new DataTable(typeof(T).Name);

        //Get all the properties

        PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
       
        foreach (PropertyInfo prop in Props)
        {

            //Setting column names as Property names

            dataTable.Columns.Add(prop.Name);

        }

        foreach (T item in items)
        {

            var values = new object[Props.Length];

            for (int i = 0; i < Props.Length; i++)
            {

                //inserting property values to datatable rows

                values[i] = Props[i].GetValue(item, null);

            }

            dataTable.Rows.Add(values);

        }
        return dataTable;
    }

推荐答案

看看这个:将列表转换为数据表 [ ^ ] - 这是我使用的方法。
Have a look at this: Converting a List to a DataTable[^] - it's the method I use.


嗯,我是强烈建议阅读:如何:实现CopyToDataTable< T>通用类型T不是DataRow的地方Microsoft Docs [ ^ ]



如果您的列表只是列表< string> ,您可以使用: DataTable.LoadDataRow() [ ^ ] + CopyToDataTable() [ ^ ]方法。



请参阅:

Well, i'd strogly recommend to read this: How to: Implement CopyToDataTable<T> Where the Generic Type T Is Not a DataRow | Microsoft Docs[^]

If your list is just a List<string>, you can use: DataTable.LoadDataRow()[^] + CopyToDataTable()[^] method.

See:
List<string> mylist = new List<string>() {"1830","950","902","540"};

DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("item", typeof(string)));
dt = mylist
	.Select(x=> dt.LoadDataRow(new object[]{x}, false))
	.CopyToDataTable();





详情请见:从查询创建DataTable(LINQ to DataSet) Microsoft Docs [ ^ ]



祝你好运!



For further details, please see: Creating a DataTable From a Query (LINQ to DataSet) | Microsoft Docs[^]

Good luck!


这篇关于如何使用扩展方法将列表转换为数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆