Nagarajaswamy

Nagarajaswamy

  • NA
  • 86
  • 13.9k

how to avoid nested for looping for improved performance?

Mar 28 2017 5:32 AM
Hi,
 
I am using the below code to bind data to datagrid in WPF. since I have huge data and I am using nested for loop, it is consuming more time to process it and display it using the datagrid. 
 
Table structure is as below:

Col1 Col2 Col3 Col4
1        2       1     [{"Name":"A1","Vol":10},{"Name":"A2","Vol":1},{"Name":"A3","Vol":11}]
1        2       2     [{"Name":"A1","Vol":20},{"Name":"A2","Vol":2},{"Name":"A3","Vol":22}]
1        2       3     [{"Name":"A1","Vol":30},{"Name":"A2","Vol":3},{"Name":"A3","Vol":33}]
1        3       1     [{"Name":"A1","Vol":40},{"Name":"A2","Vol":4},{"Name":"A3","Vol":44}]
1        3      2      [{"Name":"A1","Vol":50},{"Name":"A2","Vol":5},{"Name":"A3","Vol":55}] 
 
 All columns are of type nvarchar. Since col4 has huge data, Im storing data in JSON format.
(because each set has to be represented as a column in the output window)

Output that I am expecting is,

Col1 Col2 Col3  A1  A2  A3
1      2      1     10   1   11
1      2      2     20   2   22
1      2      3     30   3   33
1      3      1     40   4   44
1      3      2     50   5   55

Table can contain data upto 50,000 rows and Col4 can contain data upto 300 sets
(here I have mentioned only 3 set of data for col4)


In order to perform this operation for 50,000 data and 300 set of data in col4, It has to take less than a second of time.
 
 please find the below code and suggest me the alternative for this.
 

public List<SampleJSONTable> LoadDataGridViewToTestUpdate()
{
DataEntities ob = new DataEntities();
var result = (from c in ob.SampleJSONTable
select c);
return result.ToList<SampleJSONTable>();
}

private DataTable LoadDataToTable()
{
Repository obj = new Repository();
List<SampleJSONTable> tableData = obj.LoadDataGridViewToTestUpdate();


var dataTable = new DataTable();

dataTable.Columns.Add(new DataColumn("Col1", typeof(int)));
dataTable.Columns.Add(new DataColumn("Col2", typeof(string)));
dataTable.Columns.Add(new DataColumn("Col3", typeof(string)));
//dataTable.Columns.Add(new DataColumn("Col4", typeof(string)));



foreach (var item in tableData.ToList<SampleJSONTable>())
{
var dataRow = dataTable.NewRow();

dataRow["Col1"] = item.Col1;
dataRow["Col2"] = item.Col2;
dataRow["Col3"] = item.Col3;

IEnumerable<Column4Data> deserializedProduct = Newtonsoft.Json.JsonConvert.DeserializeObject<IEnumerable<Column4Data>>(item.Col4);

foreach (var jsonItem in deserializedProduct)
{

if (!dataTable.Columns.Contains(jsonItem.Name.ToString()))
{
dataTable.Columns.Add(new DataColumn(jsonItem.Name.ToString(), typeof(int)));
}
dataRow[jsonItem.Name.ToString()] = jsonItem.Vol;
}

dataTable.Rows.Add(dataRow);
}

return dataTable;
}
}

 

Answers (4)