LaserBeak
LaserBeak

Reputation: 3285

How do I correctly use .OrderBy() in this scenario

I have the interface

   public interface IStoreItem
    {

        decimal Price { get; }
    }

And the class which implements it.

public class ProductShell : IStoreItem
    {

        EFDbContext repository = new EFDbContext();


        public int ShellID { get; set; }
        public bool? Published { get; set; }

        public decimal Price { get { return repository.ShellMembers.Where(x => x.ShellID == ShellID).Select(x => x.Product.ListPrice).Sum();  } }

    }

The price is set correctly, however when I attempt to do an OrderBy by ascending (default) I do not see any changes in the list and items remain in their old positions. Being ProductShell objects where the Price property is set are still being ordered from highest to lowest and not vice versa.

            List<IStoreItem> StoreItems = new List<IStoreItem>();

            StoreItems.AddRange(repository.ProductShells.Where(x => x.Published != null));

            StoreItems.OrderBy(x => x.Price);

Upvotes: 0

Views: 410

Answers (1)

Cheng Chen
Cheng Chen

Reputation: 43503

.OrderBy creates a new sequence. You should use List.Sort here. Or sort it before adding to the list:

List<IStoreItem> StoreItems = repository.ProductShells
     .Where(x => x.Published != null)
     .OrderBy(x => x.Price)
     .ToList<IStoreItem>();

Upvotes: 4

Related Questions