Raghu Mohan

Raghu Mohan

  • NA
  • 14
  • 11.8k

C# Looping over DataTable, compare with previous row

Oct 20 2015 4:34 PM
Hi I have attached two word documents
 
1.Currentoutput
2.Requiredoutput
 
I have generated "CurrentOutput" document using Open XML. I have heading1 and heading 2 stylings for the headings. If you look at  the Currentoutput document you can see that they are repeated for the contents within the category. Instead I want single heading 1 and heading2. Below is the code which I am using to generate current output file.
 
Referring the currentoutput and the required output will give a clear understanding. 
 
Table table = GeneratingTable();
DataTable dta = ds.Tables["a"];
DataTable dtb = ds.Tables["b"];
foreach (DataRow dr in dtb.Rows)
{
TableRow tablerow = CreateRow(table);
int aID = Convert.ToInt32(dr["a_Id"]);
string aName = GetAName(aID, dta);
string bValue = dr["b_Text"].ToString();
if (!string.IsNullOrEmpty(aName))
{
if (aName == "something")
{
TableCell tc = CreateCell(tablerow, aValue, "Heading1Char", true, "2880");
TableCell tc2 = CreateCell(tablerow, " ", "Heading1Char", true, "7398");
}
else if (aName == "somethingelse")
{
TableCell tc = CreateCell(tablerow, aValue, "Heading2Char", true, "2880");
TableCell tc2 = CreateCell(tablerow, " ", "Heading2Char", true, "7398");
}
else
{
TableCell tc = CreateCell(tablerow, aName, "BodyImpactRecom", true, "2880");
TableCell tc2 = CreateCell(tablerow, aValue, "BodyImpactRecom", false, "7398");
}
}
}
var myContentControl = doc.MainDocumentPart.Document.Body.Descendants<SdtBlock>()
.Where(e => e.Descendants<SdtAlias>().FirstOrDefault().Val == "myTable").FirstOrDefault();
SdtContentBlock sdtContentBlock1 = new SdtContentBlock();
sdtContentBlock1.Append(table);// Your table
myContentControl.Append(sdtContentBlock1);
doc.MainDocumentPart.Document.Save();
doc.Close();
}
Console.Read();
}
public static string GetAName(int aID, DataTable dt)
{
string aName = "";
string expression;
expression = String.Format("a_Id = {0}", aID);
DataRow[] foundRows;
// Use the Select method to find all rows matching the filter
foundRows = dt.Select(expression);
if (foundRows != null)
{
for (int i = 0; i < foundRows.Length; i++)
{
aName = foundRows[i][1].ToString();
}
}
return aName;
}
I need required output file. I know the logic we have to loop through the datatable after first iteration save the value and from the second iteration on we have to compare the value with previous value. If the value is same as previous value it should not display anything
 
 Help would be much appreciated. Thanks a lot. 
 
Can someone please answer its very urgent. Your help would be appreciated. Please and Thanks again

Attachment: sample.zip

Answers (1)