Doctor Ford
Doctor Ford

Reputation: 568

Extracting Data From DataTable

I have a DataTable that has 2 columns as a semi-colon separated list. I need a way to parse out the data from those columns and "match" them together. For example, let's take the information for James Jo - I want it to look like this when extracted:

SH11 - Shirt
HA22 - Hat
SO33 - Socks

And this is my DataTable set-up, it's all string values.

DataTable table = new DataTable();
table.Columns.Add("Name", typeof(string));
table.Columns.Add("ItemsSold", typeof(string));
table.Columns.Add("ItemIDs, typeof(string));

table.Rows.Add("James Jo", "Shirt; Hat; Socks;", "SH11; HA22; SO33");
table.Rows.Add("Jack Bo", "Pants; Scarf;", "PA44; SC55");

Upvotes: 0

Views: 48

Answers (1)

Zohar Peled
Zohar Peled

Reputation: 82474

999 times out of 1000 (and some will say even always), using delimited strings is the wrong way to represent data like this is the wrong thing to do.

Ideally, you would have one table for items, one table for names, and one table to represent the relationship between them.

However, assuming you are stuck with the design you currently have, you can get the desired result by using the string.Split() method to get arrays from the data in each table cell, like this:

var itemsSold = table.Rows[0].Field<string>("ItemsSold").Split(new string[] {", "}, StringSplitOptions.RemoveEmptyEntries);
var ItemIDs = table.Rows[0].Field<string>("ItemIDs").Split(new string[] {", "}, StringSplitOptions.RemoveEmptyEntries);

Then you would have two arrays of string - one contaiting the values of "ItemsSold" and one containing the values of "ItemIDs".

Upvotes: 1

Related Questions