2017-05-09 1 views
0

SortedList와 함께 Linq를 사용할 때 기대되는 것에 대한 설명서를 읽은 후에 혼란스러워합니다.SortedList 및 Linq

https://msdn.microsoft.com/en-us/library/ms132319(v=vs.110).aspx

나는 열거 정렬 또한 인덱스를 검색 할 수 보장,하지만 가치와 키에 대한 추측? 이 모든 사례가 안전한가요? 에서

 var list = new SortedList<DateTime, object>(); 

     //add entries here ... 

     var firstValue1 = list.Values[0]; 
     var firstValue2 = list.First().Value; 
     var firstValue3 = list.Values.First(); 

     var firstKey1 = list.Keys[list.Count-1]; 
     var firstKey2 = list.First().Key; 
     var firstKey3 = list.Keys.First(); 

     var sortedList = list.Where(x => x.Key > DateTime.Now) 
      .Select(x => x.Value); 
+0

Linq 쿼리의 요점은 실제로 무언가를 쿼리하여 '.First(). Value'가 나에게 무작위로 좋다는 것입니다. – EpicKip

+0

@EpicKip : 나는 따라 가지 않는다. 정렬 된 목록에서 첫 번째 항목을 가져 오는 대신 무작위로 만드는 이유는 무엇입니까? – Chris

+0

'SortedList 개체의 요소는 SortedList를 만들 때 지정된 특정 IComparer 구현에 따라 또는 키 자체에서 제공하는 IComparable 구현에 따라 키에 따라 정렬됩니다. – Equalsk

답변

0
당신은 여기에 소스 코드를 확인할 수 있습니다

:

https://referencesource.microsoft.com/#System/compmod/system/collections/generic/sortedlist.cs,374aa21b960ae2e2

경우 : 분명히

https://referencesource.microsoft.com/#System/compmod/system/collections/generic/sortedlist.cs,de670561692e4a20

에서, Keys 속성은이 클래스의 인스턴스 주위에 단지 래퍼입니다 GetEnumerator() 메서드를 보면 SortedListKeyEnumerator이라는 것을 볼 수 있습니다. 여기에 대한 소스 코드입니다 :

https://referencesource.microsoft.com/#System/compmod/system/collections/generic/sortedlist.cs,a4492235f85c77d8

를 지금까지 내가 말할 수있는, 포함 된 SortedList의 키를 통해이 단지 반복의 MoveNext().

Values과 동일한 방식으로 확인할 수 있습니다.

+0

소스 코드가 변경 될 수 있으며, 문서화 된 보증은 변경 될 수 없습니다. :) – Stig

+0

@Stig 문서 보증도 변경됩니다. C# 및 .NET은 실제로 작게는 이전에 큰 변화를 가져 왔습니다. – Servy

0

Enumerable.cs의 소스 코드를 보면, 술어가없는 과부하는 단순히 IList로 소스를 처리하려고 시도하며, 작동하지 않으면 열거자를 사용하여 첫 번째 요소를 반환한다는 것을 알 수 있습니다 . 인덱스 및 열거 모두 적절한 (분류) 결과를 얻을 수 있도록 SortedList 클래스에 의해 내부적으로 처리 할 생각됩니다

술어 과부하가 모든에 대해 술어를 실행하는 약간 다른 작품

public static TSource First<TSource>(this IEnumerable<TSource> source) { 
      if (source == null) throw Error.ArgumentNull("source"); 
      IList<TSource> list = source as IList<TSource>; 
      if (list != null) { 
       if (list.Count > 0) return list[0]; 
      } 
      else { 
       using (IEnumerator<TSource> e = source.GetEnumerator()) { 
        if (e.MoveNext()) return e.Current; 
       } 
      } 
      throw Error.NoElements(); 
     } 
첫 번째 일치 항목을 찾으려는 열거자를 사용하는 항목 :

public static TSource First<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) { 
     if (source == null) throw Error.ArgumentNull("source"); 
     if (predicate == null) throw Error.ArgumentNull("predicate"); 
     foreach (TSource element in source) { 
      if (predicate(element)) return element; 
     } 
     throw Error.NoMatch(); 
    } 

어느 경우이든 동일한 (정렬 된) 결과가 표시되어야합니다.