2014-03-04 29 views
0

嗨我想基於使用Linq orderby命令給定字段的值的對象數組。無法使用Orderby Linq c排序對象的數組#

這裏是我的代碼:

LogDataPopulator[] arrLogPopulators = new LogDataPopulator[logCounter]; 
int counter = 0; 
foreach (DateTime d in dtTimeVal) 
{ 
    arrLogPopulators[counter] = new LogDataPopulator(); 
    arrLogPopulators[counter].messageDateTime = dtTimeVal[counter]; 
    arrLogPopulators[counter].messageContent = contentVal[counter]; 
    arrLogPopulators[counter].messagelevel = levelVal[counter]; 
    arrLogPopulators[counter].messagepublisher = publisherVal[counter]; 
    counter++; 
} 
LogDataPopulator[] sorted = new LogDataPopulator[logCounter]; 
sorted = arrLogPopulators.OrderBy(item => item.messageDateTime).ToArray(); 

但是我得到一個空引用異常錯誤

System.NullReferenceException是未處理
消息=對象引用不設置到對象的實例。
源= McLogViewer

任何想法,我應該如何使用OrderBy條款,我在做什麼錯?

任何幫助將不勝感激。另外,我可以通過將其轉換爲字典來排序對象數組,但這不會達到我的目的,因爲我試圖在綁定到LogDataPopulator類的Windows窗體gridview中顯示內容。

+3

那麼什麼是堆棧跟蹤顯示?一直都不清楚問題在於排序中...'messageDateTime'的類型是什麼? –

+0

它可能是OrderBy返回NULL並在ToArray()上拋出異常;除去ToArray()並查看異常是否仍然存在。 – CathalMF

+0

您好messageDateTime是DateTime類型 – user3370268

回答

1

確保dtTimeVal的長度等於arrLogPopulators的長度。否則,您將最終得到未初始化的成員arrLogPopulators,當您嘗試對其messageDateTime屬性進行排序時,將拋出NullReferenceException。

0

應該有這樣的工作:

var sorted = (from d in dtTimeVal 
    let arrLogPopulator = new LogDataPopulator(dtTimeVal[counter], contentVal[counter], 
            levelVal[counter], publisherVal[counter]) 
    orderby arrLogPopulator.messageDateTime 
    select arrLogPopulator).ToArray() 

在你LogDataPopulator類的構造函數:

public LogDataPopulator(//some arguments...) 
{ 
    this.messageDateTime = //arg1; 
    this.messageContent = //arg2; 
    this.messagelevel = //arg3; 
    this.messagepublisher = //arg4; 
    //others arguments... 
}