How to sort an IEnumerable

后端 未结 4 873
执笔经年
执笔经年 2020-12-24 03:59

How can I sort an IEnumerable alphabetically. Is this possible?

Edit: How would I write an in-place solution?

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-24 04:47

    We can't always do it in-place, but we detect when it's possible:

    IEnumerable SortInPlaceIfCan(IEnumerable src, IComparer cmp)
    {
      List listToSort = (src is List) ? (List)src : new List(src);
      listToSort.Sort(cmp);
      return listToSort;
    }
    IEnumerable SortInPlaceIfCan(IEnumerable src, Comparison cmp)
    {
      return SortInPlaceIfCan(src, new FuncComparer(cmp));
    }
    IEnumerable SortInPlaceIfCan(IEnumerable src)
    {
      return SortInPlaceIfCan(src, Comparer.Default);
    }
    

    This uses the following handy struct:

    internal struct FuncComparer : IComparer
    {
      private readonly Comparison _cmp;
      public FuncComparer(Comparison cmp)
      {
          _cmp = cmp;
      }
      public int Compare(T x, T y)
      {
          return _cmp(x, y);
      }
    }
    

提交回复
热议问题