简体   繁体   中英

Better way to use data set in C#

We have created a custom dataset and populating it with some data.

Before adding data, we are adding columns in the data set as follows

DataSet archiveDataset = new DataSet("Archive");
DataTable dsTable = archiveDataset.Tables.Add("Data");
dsTable.Columns.Add("Id", typeof(int));
dsTable.Columns.Add("Name", typeof(string));
dsTable.Columns.Add("LastOperationBy", typeof(int));
dsTable.Columns.Add("Time", typeof(DateTime))

Once the Dataset is create, we are filling values as follows

 DataRow dataRow = dsTable.NewRow();
 dataRow["Id"] = source.Id;
 dataRow["Name"] = source.Name;
 dataRow["LastOperationBy"] = source.LastOperationBy;
 dataRow["Time"] = source.LaunchTime;

Is there any better and managed way of doing this. can I make the code more easy to write using enum or anything else to reduce the efforts?

You could try using a Typed Dataset .

This should get rid of the ["<column_name>"] ugliness.

If the dataset has a structure similar to tables in a database, then Visual Studio makes it really easy to create one: just click Add -> New Item somewhere in the solution and choose DataSet . VS will show a designer where you can drag tables from your server explorer.

Update (after response to Simon's comment): A typed dataset is in fact an XSD (XML Schema Definition). What I did in a similar case was:

  • created an empty DataSet (using Add -> New Item -> DataSet )
  • opened the newly created file with a text editor (by dafault, in VS it shows the XSD designer)
  • paste the XSD that I had created manually

You could also choose to use the designer to create the schema.

Considering your comment "I am using Dataset to export data to a XML file" I recommend using a different technology such as

Or better yet of is doesnt have to be XML (and you only want hierarchical readable text consider JSON instead http://james.newtonking.com/pages/json-net.aspx

You can bind dataset in two way first one is using database second one is add manually. After create column for dataset you can add using Loops you can add it if you have 10000 of entries.

You can use Reflection . Another option is to use EntityFramework or NHibernate to map the columnnames and datastructure columns and then avoid these code to fill each field manually. But they will add more complexity. Also Performance wise the your code is better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM