0

I am generating a report from a stored proc that outputs a DataTable in the following format:

id    |    date    | value
--------------------------
0     |   5/18/11  | 10
0     |   5/19/11  | 13
0     |   5/20/11  | 7
0     |   5/21/11  | 1
1     |   5/18/11  | 9
1     |   5/19/11  | 34
1     |   5/20/11  | 5
1     |   5/21/11  | 6

where the id corresponds to an employee's id number.

I don't like dealing with raw DataTables throughout my code, but I don't know the best way to represent such information most effectively in some sort of model object in C#. How would you do it?

tereško
  • 58,060
  • 25
  • 98
  • 150
Davis Dimitriov
  • 4,159
  • 3
  • 31
  • 45

2 Answers2

1

Simply make a class...

public class ReportModel 
{
  public int ID {get; private set;}
  public DateTime Date {get; private set;}
  public int Value {get; private set;}

  private ReportModel() {}

  public static ReportModel FromDataRow(DataRow dataRow)
  {
       return new ReportModel
       {
            ID = Convert.ToInt32(dataRow["id"]),
            Date = Convert.ToDateTime(dataRow["date"]),
            Value = Convert.ToInt32(dataRow["value"])
       };
  } 

  public static List<ReportModel> FromDataTable(DataTable dataTable)
  {
       var list = new List<ReportModel>();

       foreach(var row in dataTable.Rows)
       {
            list.Add(ReportModel.FromDataRow(row);
       }

       return list;
  }
}

You can also use AutoMapper to encapsulate the mapping from DataRow to ReportModel.

ctorx
  • 6,841
  • 8
  • 39
  • 53
  • but this doesn't take into account the grouping of id's somehow to make it easier to work with. What I am wondering is how do people typically model such a class with C#? – Davis Dimitriov May 18 '11 at 17:33
  • You could use a Dictionary object for this...the key in the dictionary would be the ID and the Value in the dictionary could be a custom type that has two properties (date and value). – ctorx May 18 '11 at 20:07
0

Take a look at this thread, How to create CSV Excel file C#?

Community
  • 1
  • 1
gnome
  • 1,113
  • 2
  • 11
  • 19