KamikyIT
KamikyIT

Reputation: 314

Fill DataSet from List of class Items

I've searched SO for common questions, but they didn't match my task. I have a class with many(about 50) ValueTyped properties. And there are needs to fill a new DataSet object with class's properties.

For example, if I have this:

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

I need a two functions to return

  1. Filled DataSet with a single row for single MyClass item.

  2. Filled DataSet with a multiple rows for multiple MyClass items.


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

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

I've tried many solutions like below, but it's unable to compile since DataRow doesn't have public constructor.

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

Upvotes: 0

Views: 6044

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460208

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;
    }
}

Upvotes: 2

Related Questions