简体   繁体   中英

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);

.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>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM