Sorry if this is a duplicate but I can't find a StackOverflow post that works for me.

I'm getting miffed over learning how to use list model w/ linq. My problem here is sorting by DateTime had no effect. I'm using .NET framework v4.5. I'm using SQL DataReader to read data into list model, but instead of writing/posting sql object, I'm gonna manually specify the adding of data to list model manually for this posting.

public MyInventory : IDisposable { public MyInventory { PurchaseId = -1; StockDate = null; } public void Dispose() { //PurchaseId... StockDate = null; } public long PurchaseId { get; set; } public DateTime? StockDate { get; set; } } List<MyInventory> modelMyInventory = new List<MyInventory>(); modelMyInventory.Add(new MyInventory { PurchaseId = 2, StockDate = DateTime.Parse("01-02-2010") }); modelMyInventory.Add(new MyInventory { PurchaseId = 5, StockDate = DateTime.Parse("01-03-2011") }); modelMyInventory.Add(new MyInventory { PurchaseId = 7, StockDate = DateTime.Parse("01-01-2010") }); modelMyInventory.OrderByDescending(m => m.StockDate); 

Thanks...

5

3 Answers

OrderByDescending method does not order in place, you need to re-assign again:

modelMyInventory = modelMyInventory.OrderByDescending(m => m.StockDate); 
1
modelMyInventory.OrderByDescending(m => m.StockDate); 

does not actually sort the modelMyInventory object. Instead, it returns a new enumerable that is sorted. So you should write:

modelMyInventory = modelMyInventory.OrderByDescending(m => m.StockDate); 
modelMyInventory.OrderByDescending(m => m.StockDate); 

This does not reorder modelMyInventory. This returns a new enumeration ordered by StockDate.

You can either create a new variable or store the new list in the same variable:

var modelSorted = modelMyInventory.OrderByDescending(m => m.StockDate); 

or

modelMyInventory = modelMyInventory.OrderByDescending(m => m.StockDate).ToList(); 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.