【问题标题】:Sorting List<T> inside subclass with LINQ使用 LINQ 在子类中对 List<T> 进行排序
【发布时间】:2011-05-25 15:13:24
【问题描述】:

我知道我可以像这样对列表进行排序

var result = List<T>.OrderBy(value => value.property);

但是假设我有这样的东西

    class Stock
    {
        public Guid ID { get; set; }
        public string Description { get; set; }
    }

    class StockList : List<Stock>
    {
        public enum SomeEnum
        {
            SomeOtherValue = 0,
            SomeOtherOtherValue
        }
        //What if I want method like this using LINQ?
        public void Sort(SomeEnum sortBy)
        {
            switch (sortBy) 
            {
                case SomeValue.SomeOtherOtherValue:
                    //Sort one way
                    break;
                case SomeValue.SomeOtherValue:
                    //Sort another
                    break;
            }
        }
    }

this.OrderBy()(我假设其他 LINQ 扩展)返回一个 OrderedCollection 并且似乎不会影响原件。所以我认为我的做法是错误的?

【问题讨论】:

  • 请注意,当您执行List&lt;T&gt;.OrderBY(...) 时,您并未对列表进行排序,而是返回了一个可按顺序枚举列表的可枚举。即列表不受影响(如您所见)。

标签: c# linq sorting collections ienumerable


【解决方案1】:

您可以使用List.Sort( )。这将对列表进行就地排序。

【讨论】:

    【解决方案2】:

    你可以的

    this.Sort(new Comparison<Stock>((x,y) => x.Description.CompareTo(y.Description)));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-14
      • 1970-01-01
      • 2021-12-25
      • 1970-01-01
      • 2019-12-13
      • 2019-07-02
      • 1970-01-01
      相关资源
      最近更新 更多