リストがあるとします:-
var animals = new[] {"ant", "bear", "bee", ...... "monkey", ...... "zebra"};
ミツバチとサルの間を反復する最も簡単な方法は何ですか?
何度も歯ぎしりをしたり、髪を引っ張ったり、頭を壁にぶつけたりした後、自分のイテレータを作成する簡単な方法でそれを行うことにしました。
public static class LinqExtensions {
public static IEnumerable<T> InRange<T>(this IEnumerable<T> list, T first, T last) {
int i = 0;
while (list.Count() > i && ! list.ElementAt(i).Equals(first))
++i;
while (list.Count() > i && ! list.ElementAt(i).Equals(last))
yield return list.ElementAt(i);
if (list.Count() > i && list.ElementAt(i).Equals(last))
yield return list.ElementAt(i);
}
}
現在、以下は完全に機能します:-
foreach (var x in animals.InRange("bee", "monkey")) {
....
}