List Model --> Orderbydescending System. Datetime Does Not Work?

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

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.

Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest