[c#] IEnumerable <string>을 정렬하는 방법

IEnumerable<string>알파벳순으로 정렬하려면 어떻게해야합니까 ? 이게 가능해?

편집 : 내부 솔루션을 어떻게 작성합니까?



답변

다른 열거 형을 정렬하는 것과 같은 방식으로 :

var result = myEnumerable.OrderBy(s => s);

또는

var result = from s in myEnumerable
             orderby s
             select s;

또는 (대소 문자 무시)

var result = myEnumerable.OrderBy(s => s,
                                  StringComparer.CurrentCultureIgnoreCase);

LINQ에서 평소처럼 이렇게하면 열거 될 때 원래 IEnumerable <T>의 요소를 정렬 된 순서로 반환하는 새 IEnumerable <T>가 생성됩니다. IEnumerable <T>를 제자리에 정렬하지 않습니다.


IEnumerable <T>는 읽기 전용입니다. 즉, 요소를 검색 만 할 수 있지만 직접 수정할 수는 없습니다. 문자열 컬렉션을 제자리에서 정렬하려면 먼저 IEnumerable <string>을 구현하는 원래 컬렉션을 정렬하거나 IEnumerable <string>을 정렬 가능한 컬렉션으로 먼저 전환해야합니다.

List<string> myList = myEnumerable.ToList();
myList.Sort();

귀하의 의견에 따라 :

_components = (from c in xml.Descendants("component")
               let value = (string)c
               orderby value
               select value
              )
              .Distinct()
              .ToList();

또는

_components = xml.Descendants("component")
                 .Select(c => (string)c)
                 .Distinct()
                 .OrderBy(v => v)
                 .ToList();

또는 (나중에 목록에 항목을 더 추가하고 정렬 된 상태로 유지하려는 경우)

_components = xml.Descendants("component")
                 .Select(c => (string)c)
                 .Distinct()
                 .ToList();

_components.Add("foo");
_components.Sort();


답변

불가능하지만 그렇지 않습니다.

기본적으로, 어떤 종류의 방법은 당신을 복사하는 것입니다 IEnumerable으로 List정렬, List다음에있는 정렬 된 목록 반환 IEnumerable뿐만 아니라를 IList.

즉,의 “무한히 계속”속성을 잃었 IEnumerable지만 어쨌든 그런 식으로 정렬 할 수 없습니다.


답변

myEnumerable = myEnumerable.OrderBy(s => s);


답변

항상 제자리에서 할 수는 없지만 가능한 경우 감지합니다.

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

이것은 다음과 같은 편리한 구조체를 사용합니다.

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


답변