假设我有一个清单: -
var animals = new[] {"ant", "bear", "bee", ...... "monkey", ...... "zebra"};
在蜜蜂和猴子之间进行迭代的最简单方法是什么?
答案 0 :(得分:3)
var myAnimals = animals.SkipWhile(a => a != "bee").TakeWhile(a => a != "monkey").ToList();
答案 1 :(得分:0)
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")) {
....
}