【问题标题】:Fill DataSet from List of class Items从类项列表中填充数据集
【发布时间】:2017-07-24 22:25:34
【问题描述】:

我已经搜索了常见问题,但它们与我的任务不匹配。 我有一门有很多(大约 50 个)ValueTyped 属性的课程。 并且需要用类的属性填充new DataSet 对象。

例如,如果我有这个:

public partial class MyClass
{
    public int Id {get; set;}
    public string Name {get; set;}
    // and other public properties
}

我需要两个函数来返回

  1. 为单个 MyClass 项填充单行的数据集。

  2. 为多个 MyClass 项填充多行的数据集。


public partial class MyClass
{
    public DataSet GenerateDataSet(MyClass source);

    public DataSet GenerateDataSet(IEnumerable<MyClass> source);
}

我尝试了很多类似下面的解决方案,但由于DataRow 没有公共构造函数,所以无法编译。

var ds = new DataSet();
ds.Tables.Add(new DataTable("DataTableName"));
var table = ds.Tables[0];
table.Rows.Add(new DataRow(new DataRowBuilder(table, 0)));

【问题讨论】:

    标签: c# dataset


    【解决方案1】:
    public partial class MyClass
    {
        public DataSet GenerateDataSet(MyClass source)
        {
            return GenerateDataSet(new[] { source });
        }
    
        public DataSet GenerateDataSet(IEnumerable<MyClass> source)
        {
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            ds.Tables.Add(dt);
            dt.Columns.Add("Name");
            dt.Columns.Add("Id", typeof(int));
            // other columns...
            foreach (MyClass c in source)
            {
                DataRow dr = dt.Rows.Add();
                dr.SetField("Name", c.Name);
                dr.SetField("Id", c.Id);
                // other properties
            }
            return ds;
        }
    }
    

    【讨论】:

    • DataRow dr = dt.Rows.Add(); 那是我上次看的那个神奇的代码字符串。非常感谢!
    • @KamikyIT:你也可以使用dt.Rows.Add(c.Name, c.Id, ...)。但我更喜欢我的方法,因为这样您就可以指定不易出错的列及其值。
    • 我会将您的答案标记为正确(因此需要时间)。再次感谢!
    • 如果你想成为超级 c# 的花哨,请考虑“隐式”运算符:docs.microsoft.com/en-us/dotnet/csharp/language-reference/…
    猜你喜欢
    • 1970-01-01
    • 2021-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多