C#-按十进制值对列表进行排序

我有一个Product类的列表,我想按计算出的价格对其进行排序。

    public class Product
    {
        public decimal Price { get; set; }
        public int Amount { get; set; }

        public decimal CalculatePrice
        {
            get
            {
                return Price * Amount;
            }
        }
    }

我已经尝试了以下方法,但是不起作用:

    products.OrderBy(p => p.CalculatePrice);
评论
  • non_et
    non_et 回复
    • You have LINQ's extension-methods and List<T>s member methods confused:
      • .OrderBy is a LINQ extension method that returns a lazily-evaluated IEnumerable<T> that represents a sorted version of the original List<T>, however it does not perform any immediate sorting nor alter/change ("mutate").
        • .OrderBy uses a Func<T,TSortBy> (or Expression<Func<T,TSortBy>>) to choose a single property to compare.
      • List<T> has a method Sort which re-orders the List<T> in-place without returning a new list or new view of the same list.
        • .Sort uses a Func<T,T,Int32> as a custom comparator.