Reputation: 174
I want to fill data table like following image Image. I tried to get that format by the following code.
What I Tried: Created Class like
public class SomeDetails
{
public string username { get; set; }
public List<string> SetA{ get; set; }
public List<string> SetB{ get; set; }
}
and code: I created one method which takes parameters user ,SetA,SetB(here Seta, SetB are Lists). I need to call following method of code for multiple times.
var percoll=new SomeDetails();
percoll.username=user;
percoll.SetA=SetA;
percoll.SetB=SetB;
//dt repressents DataTable
if (percoll.SetA.Count > 0 && percoll.SetB.Count > 0)
{
dt.Rows.Add(user, SetA[0], SetB[0]);
var rowcount =SetA.Count > SetB.Count ? SetA.Count : SetB.Count;
dt = FillDataTable(rowcount, dt, perColl);
}
else if (percoll.SetA.Count > 0 && percoll.SetB.Count == 0)
{
//Add first row to datatable to get image Format
//calculate row count
// call FillDataTable
}
else if (percoll.SetA.Count == 0 && percoll.SetB.Count > 0)
{
//Add first row to datatable to get image Format
//calculate row count
// call FillDataTable
}
else
{
dt.Rows.Add(user.Key,"-", "-");
}
And FillDatatable is like following manner.
private DataTable FillDataTable(int rowcount, DataTable dt, SomeDetails perColl)
{
for (int i = 1; i < rowcount; i++)
{
string A= "";
string B= "";
if (i < perColl.SetA.Count)
{
A= perColl.SetA[i];
}
if (i < perColl.SetB.Count)
{
B= perColl.SetB[i];
}
dt.Rows.Add("", A, B);
}
return dt;
}
Problem: I want to add another column SetC to above image. If I Use above method, I need to check 9 if-else conditions, which is not a good choice. Finally DataTable should be like this Final Image
need Suggestions for better code.
Upvotes: -1
Views: 74
Reputation: 1947
Really not sure what you are doing with all these if-else statements but this should do the same as your code.
foreach(var datail in AllDetails) { //assuming you have a list of all users
// get the max row count of all 3 data sets
var rows = Math.max(datail.SetA.Count, Math.max(datail.SetB.Count, detail.SetC.Count));
// iterate to "end" of all datasets
for (var i = 0; i < rows; i++) {
// show name only for first row
var name = i == 0 ? detail.username : "";
// if list has more elements than actual counter i, access the i'th element - otherwise empty string
var a = i < datails.SetA.Count ? datails.SetA[i] : "";
var b = i < datails.SetB.Count ? datails.SetB[i] : "";
var c = i < datails.SetC.Count ? datails.SetC[i] : "";
// add values to row
dt.Rows.Add(name, a, b, c);
}
}
Upvotes: 2