I'm trying to exchange the ordering of particular items of an IEnumerable
.
Given an IEnumerable<int> a;
of the elements:
1, 2, 3, 4, 5
and what I want to do is write a exchange iterator which resulting a.Exchange(1, 2)
in:
1, 3, 2, 4, 5
But I don't want the enumerable be iterated more than once with this simple purpose. What I have so far is:
public static IEnumerable<T> Exchange<T>(
this IEnumerable<T> source, int index1, int index2) {
var i=0;
foreach(var y in source) {
if(index1==i) {
var j=0;
foreach(var x in source) {
if(index2==j) {
yield return x;
break;
}
++j;
}
}
else {
if(index2==i) {
var j=0;
foreach(var x in source) {
if(index1==j) {
yield return x;
break;
}
++j;
}
}
else {
yield return y;
}
}
++i;
}
}
Here's a assumption that index1
and index2
wouldn't exceed the elements of the enumerable. The code done the work of exchange(the ordering) in most cases, but it does iterate more than once. Note index1
and index2
might not be the real indices of source
, they would be the Mth
and Nth
element when the enumeration occurs.
ToArray
or ToList
may also increase the times of iteration.