例如我必须序列:
IEnumerable<float> List1 = new float[] {
0f, 0.1f, 0.5f, 0.9f, // < 1
1f, 1.1f, 1.5f, 1.9f, // < 2
2f, 2.9f // < 3
};
IEnumerable<int> List2 = new int[] {
1,
2,
3,
4
};
我需要得到下一个结果:
0f, 0.1f, 0.5f, 0.9f, 1,
1f, 1.1f, 1.5f, 1.9f, 2,
2f, 2.9f, 3,
4
我写了两个函数,但他们并不懒惰!
private static IEnumerable<object> Merge(IEnumerable<float> list1, IEnumerable<int> list2) {
var queue1 = new Queue<float>( list1 ); // it is not lazy!!
var queue2 = new Queue<int>( list2 );
while (queue1.Any() && queue2.Any()) {
if (queue1.Peek() < queue2.Peek()) {
yield return queue1.Dequeue();
} else {
yield return queue2.Dequeue();
}
}
while (queue1.Any()) {
yield return queue1.Dequeue();
}
while (queue2.Any()) {
yield return queue2.Dequeue();
}
}
private static IEnumerable<object> Merge2(IEnumerable<float> list1, IEnumerable<int> list2) {
var queue1 = new Queue<float>( list1 ); // it is not lazy!!
foreach (var item2 in list2) {
while (queue1.Any() && queue1.Peek() < item2) {
yield return queue1.Dequeue();
}
yield return item2;
}
}
我怎样才能通过惰性评估来做到这一点?