Lookback logic in a dataset

  • Thread starter Thread starter Joe
  • Start date Start date
J

Joe

I have a dataset as below. I want to iterate through the dataset
comparing the value of the Code column to the value in the previous
row. If they are the same then I want to concatenate the value of the
Desc column in my current row to that of the value in the previous row.
If the value of Code is different to the value in the previous row then
I want to output the row to a dataset. I managed to achieve this
functionality but in a very messy way I'm sure there must be a more
elegant solution to what I have come up with.

Can anyone come up with a simple algorithm to solve this?

Input dataset

ItemNum Code Desc
1 A Apple
2 A Cider
3 A Scrumpy
4 B Strawberry

Resulting dataset
Code Desc
A Apple Cider Scrumpy
B Strawberry


Joe
 
My example assumes that you are the data store in a table called "Table1"

string prevCode;
DataTable table = ds.Tables["Table1"];
DataRow row = table.Rows[0];
prevCode = (string)row["Code"];
for(int i = 1; i < table.Rows.Count; i++)
{
row = table.Rows;
if(row["Code"] == prevCode)
{
(table.Rows[i-1])["Desc"] = String.Concat((table.Rows[i-1])["Desc"],
row["Desc"]);
table.Rows.RemoveAt(i);
i -= 1;
}
}

hope it helps,
Ivan Wong
 
just wanna make some correction for my post

Ivan Wong said:
My example assumes that you are the data store in a table called "Table1"

string prevCode;
DataTable table = ds.Tables["Table1"];
DataRow row = table.Rows[0];
prevCode = (string)row["Code"];
for(int i = 1; i < table.Rows.Count; i++)
{
row = table.Rows;
if(row["Code"] == prevCode)
{
(table.Rows[i-1])["Desc"] = String.Concat((table.Rows[i-1])["Desc"],
row["Desc"]);
table.Rows.RemoveAt(i);
i -= 1;
}

else
{
prevCode = row["Code"];
}
 
Ivan Wong said:
My example assumes that you are the data store in a table called "Table1"

string prevCode;
DataTable table = ds.Tables["Table1"];
DataRow row = table.Rows[0];
prevCode = (string)row["Code"];
for(int i = 1; i < table.Rows.Count; i++)
{
row = table.Rows;
if((string)row["Code"] == prevCode)
{
(table.Rows[i-1])["Desc"] = String.Concat((table.Rows[i-1])["Desc"],
row["Desc"]);
table.Rows.RemoveAt(i);
i -= 1;
}

else
{
prevCode = (string) row["Code"];
}
 
Thanks Ivan - this works very well and is three times less code than I
had previously! Thank you

Joe
 
Back
Top