I have several classes
public class A { public string A1; public string A2; public string A3; }
public class B { public string B1; public string B2; }
public class C { public string C1; public string C2; public string C3; public string C4; }
And a dataSource class
public class DataSource
{
[Description("A")]
public List<A> LstA;
[Description("B")]
public List<B> LstB;
[Description("C")]
public List<C> LstC;
}
Here is what I want to do , read a string with "A" "B" "C", If I read an "A", Then I create a table withDataSource.LstA
which has three columns A1
A2
A3
.If I read a "B", Then I create a table whith DataSource.LstB
which has two columns B1
B2
and so on.
Here is how I made it
public DataSet CreateTablesFromString(char[] lstchar)
{
DataSource ds = new DataSource();
DataSet dataset = new DataSet();
for(int i = 0; i < lstchar.Length; i++)
{
if(lstchar[i] == 'A')
{
dataset.Tables.Add(CreateTable(ds.LstA));
}
else if(lstchar[i] == 'B')
{
dataset.Tables.Add(CreateTable(ds.LstB));
}
else if(lstchar[i] == 'C')
{
dataset.Tables.Add(CreateTable(ds.LstC));
}
}
return dataset;
}
private DataTable CreateTable<T>(List<T> lstData)
{
PropertyInfo[] lstinfo = lstData.ElementAt(0).GetType().GetProperties();
int rowCount = lstData.Count;
int columnCount = lstinfo.Length;
DataTable dt = new DataTable();
for(int i = 0; i < columnCount; i++)
{
dt.Columns.Add();
}
for(int i = 0; i < rowCount; i++)
{
object[] row = new object[columnCount];
for(int j = 0; j < columnCount; j++)
{
row[j] = lstinfo[j].GetValue(lstData[i]);
}
}
return dt;
}
My problem is : Is there any way to avoid so many "if else"
if(lstchar[i] == 'A')
{
dataset.Tables.Add(CreateTable(ds.LstA));
}
else if(lstchar[i] == 'B')
{
dataset.Tables.Add(CreateTable(ds.LstB));
}
else if(lstchar[i] == 'C')
{
dataset.Tables.Add(CreateTable(ds.LstC));
}
Is there a way to figure out which list I will use without "ifelse". Maybe use [Description] attritude? But I don't know how.