Unable to sort the array of objects using Orderby Linq c #


Hi I am trying to sort an array of objects based on the value of a given field using Linq orderby command.

Here is my code:

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];
LogDataPopulator[] sorted = new LogDataPopulator[logCounter];
sorted = arrLogPopulators.OrderBy(item => item.messageDateTime).ToArray();

I am however getting a null reference exception error

System.NullReferenceException was unhandled
Message=Object reference not set to an instance of an object.

Any idea how I should use the OrderBy clause and what I am doing wrong?

Any help would be much appreciated. Also I can sort the array of objects by casting it to a dictionary but that would not serve my purpose as I am trying to display the contents in a windows form gridview that is bound to the LogDataPopulator class.

Make sure the length of dtTimeVal is equal to the length of arrLogPopulators. Otherwise you will end up with uninitialized members of arrLogPopulators which will throw a NullReferenceException when you attempt to sort on its messageDateTime property.