Parsing DataTable Columns

  • Thread starter Thread starter Stuart Shay
  • Start date Start date
S

Stuart Shay

Hello All

In my DataTable the following data is returned

Object_IDX Object_FullName
48984232 |MS_Net|EUR|Server02
48986409 |MS_Net|EUR|Server21
48990195 |MS_Net|EUR|WKS23
48995964 |MS_Net|EUR|WKS2
48996647 |MS_Net|EUR|Test01

I want to parse out the Object_FullName and create 3 Columns in the
DataTable

Object_IDX Object_FullName Network Domain Host

oDataTable = oDataSet.Tables[0];
oDataTable.Columns.Add("Network",typeof(string));
oDataTable.Columns.Add("Domain",typeof(string));
oDataTable.Columns.Add("Host",typeof(string));

How do populate these Cols?

Results

Object_IDX Object_FullName Network Domain Host
48984232 |MS_Net|EUR|Server02 MS_Net EUR Server02

Thanks
Stuart
 
Hi Stuart,

Just do a loop through all rows. Something like that:
foreach (DataRow row in oDataSet.Tables[0].Rows)
{
string full = (string)row["Object_FullName"];
string parts = full.Split('|');
row["Network"] = parts[0];
...
}
 
You can use string expressions to define the columns:

oDataTable = oDataSet.Tables[0];
oDataTable.Columns.Add("Network",typeof(string),
"SUBSTRING(Object_FullName, 1, 6)");
oDataTable.Columns.Add("Domain",typeof(string),
"SUBSTRING(Object_FullName, 8, 3)");
oDataTable.Columns.Add("Host",typeof(string),
"SUBSTRING(Object_FullName, 11, LEN(ObjectFullName) - 11)");

I would have to completely understand the format of Object_FullName to get
the expression definition correct, but this gives you the idea.

Andrew Conrad
Microsoft Corp
http://blogs.msdn.com/aconrad/default.aspx
 
You could use a regular expression like this:

"\|(?<Network>.+)\|(?<Domain>.+)\|(?<Host>.+)$"

And use it like this:

Regex _ColumnParser = new
Regex("\|(?<Network>.+)\|(?<Domain>.+)\|(?<Host>.+)$");
Match _Match = _ColumnParser.Match(sColumnData);
if(_Match.Suceess){
oDataTable["Network"] = _Match.Groups["Network"];
oDataTable["Host"] = _Match.Groups["Host"];
oDataTable["Domain"] = _Match.Groups["Domain"];
}

This way if the length of the data changes you don't have to make changes in
code.

Remember to use System.Text.RegularExpressions for this code to work.

Any further help with regular expressions and syntaxis you can contact me or
go to

http://www.regular-expressions.info/

Hope this helps
 
Back
Top