2011-08-29 51 views
1

我需要將集合綁定到GridView,具體取決於用戶選擇的報表類型。集合創建/設計問題

每個報告都會略有不同,但使用具有許多列的相同基本結果集。在綁定之前,我想遍歷結果集並複製到一個更簡單的集合(3個字符串變量,稱爲'column1','column2','column3')。

代碼:

namespace etc.etc.etc 
{ 
    public class ReportEntity 
    { 
     public string column1 { get; set; } 

     public string column2 { get; set; } 

     public string column3 { get; set; } 
    } 
} 

List<ReportEntity> a = new List<ReportEntity>(); 
ReportEntity[] b = new ReportEntity[results.Length]; 
for (int i = 0; i < results.Length; i++) 
{ 
    //a[i].column1 = results[i].class.desc; 
    //a[i].column2 = results[i].student.firstname; 
    //a[i].column3 = results[i].timescanned.ToString(); 

    //b[i].column1 = results[i].class.desc; 
    //b[i].column2 = results[i].student.firstname; 
    //b[i].column3 = results[i].timescanned.ToString(); 
} 

取消註釋,我爲a設定值給出Index was out of range. Must be non-negative and less than the size of the collection.。 取消註釋我爲b設置的值給出Object reference not set to an instance of an object.

results肯定有很多記錄。我可能做錯了什麼?

回答

2
  • 你在第一種情況下獲得IndexOutRangeException因爲你剛剛創建列表的實例,但此列表中不包含任何元素。

  • 在第二種情況下,您獲得NullReferenceException,因爲您剛剛填充了results.Lengthnulls

你應該做的是明確創建ReportEntity的實例並放入底層數據結構中。

List<ReportEntity> a = new List<ReportEntity>(); 
ReportEntity[] b = new ReportEntity[results.Length]; 
for (int i = 0; i < results.Length; i++) 
{ 
    a.Add(new ReportEntity() {column1 = results[i].class.desc, 
           column2 = results[i].student.firstname, 
           column3 = results[i].student.firstname } 

    b[i] = new ReportEntity() {column1 = results[i].class.desc, 
           column2 = results[i].student.firstname, 
           column3 = results[i].student.firstname } 
} 

或者你也可以用你Select extenssion方法LINQ喜歡它在另一個答覆中提到。

1

要將值添加到列表,請使用Add方法。

另外,使用select從LINQ:

var a = results.Select(r => new ReportEntity { 
    column1 = r.class.desc, 
    column2 = r.student.firstname, 
    column3 = r.timescanned.ToString() 
}).ToList(); 
+0

噢。但是,那麼我是否需要該實體類上的構造函數 – cring

+0

上面的語法不需要任何其他構造函數 – flq