2009-07-04 36 views
3
私は私がそれを作るためにIEnumerableを上の拡張メソッドにこれを有効にしたいと思っどのようなリストの順序を確認する必要があり、それをこの

IsOrderedBy拡張メソッド

DateTime lastDate = new DateTime(2009, 10, 1); 
foreach (DueAssigmentViewModel assignment in _dueAssigments) 
{ 
    if (assignment.DueDate < lastDate) 
    { 
     Assert.Fail("Not Correctly Ordered"); 
    } 
    lastDate = assignment.DueDate; 
} 

ような何かが私のテストのいくつかでは

再利用可能。

私のinital考え方は、ここovious問題は、あなたが一般的な値にcompaireカントあるこの

public static bool IsOrderedBy<T, TestType>(this IEnumerable<T> value, TestType initalValue) 
{ 
    TestType lastValue = initalValue; 
    foreach (T enumerable in value) 
    { 
     if(enumerable < lastValue) 
     { 
      return false; 
     } 
     lastValue = value; 
    } 
    return true; 
} 

ました。誰もがこの方法を提案することができます。

乾杯 コリン・

答えて

5

私はそれがOrderBy方法と同様の方法署名を使用する方が理にかなっていると思います。 ..

public static bool IsOrderedBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) 
{ 
    bool isFirstPass = true; 
    TSource previous = default(TSource); 

    foreach (TSource item in source) 
    { 
     if (!isFirstPass) 
     { 
      TKey key = keySelector(item); 
      TKey previousKey = keySelector(previous); 
      if (Comparer<TKey>.Default.Compare(previousKey, key) > 0) 
       return false; 
     } 
     isFirstPass = false; 
     previous = item; 
    } 

    return true; 
} 

あなたはそのようにそれを使用することができます:

List<Foo> list = new List<Foo>(); 
... 

if (list.IsOrderedBy(f => f.Name)) 
    Console.WriteLine("The list is sorted by name"); 
else 
    Console.WriteLine("The list is not sorted by name"); 
+0

これは意味がありません。アイテムの値がソートキーと異なる可能性があるため、OrderByはデリゲートをとります。 'IsSorted'の場合、' Select'でシミュレートすることができます: 'list.Select(f => f.Name).IsSorted()' –

+0

良い点...私はそれを考えませんでした! –

+0

さて、はい、いつでも.Select()を使用してIsSorted()を呼び出すことができますが、その余分なステップを削除しないのはなぜですか? –

5

あなたは拘束を追加することができます。

where T:IComparable 

代わり<演算子を使用する次に、あなたがIComparableインターフェイスののCompareTo()メソッドを使用することができます。

1

あなたは(TestTypeTから異なっている必要がありますなぜ私が見ることができない)、このような何かを行う必要があります。

public static bool IsOrderedBy<T>(this IEnumerable<T> value, T initalValue) 
     where T : IComparable<T> { 

     var currentValue = initialValue; 

     foreach(var i in value) { 
      if (i.CompareTo(currentValue) < 0) 
       return false; 
      currentValue = i; 
     } 

     return true; 
}