Reputation: 40032
I have something like this:
long[] f = new long[4]{1,10,100,1000};
I want to divide 1000 by 100, 100 by 10 and 10 by 1
Is there a way to return results in an array with the results eg/ 10,10,10
UPDATE: This seems to confuse a few so here is another example
long[] f = new long[3]{1,2,6};
I want to divide 6 by 2 and 2 by 1 with the results in an array
Upvotes: 0
Views: 1772
Reputation: 838216
If I understand you correctly, you probably don't want to use Aggregate here but instead Pairwise:
long[] result = f.Pairwise((x, y) => y / x).ToArray();
Here is an example implementation of Pairwise:
public static IEnumerable<TResult> Pairwise<TSource, TResult>(
this IEnumerable<TSource> source,
Func<TSource, TSource, TResult> resultSelector)
{
TSource previous = default(TSource);
using (var it = source.GetEnumerator())
{
if (it.MoveNext())
previous = it.Current;
while (it.MoveNext())
yield return resultSelector(previous, previous = it.Current);
}
}
If you want the results in reverse order then add a call to Reverse
.
Upvotes: 4
Reputation: 292425
I don't think aggregate is gonna help in that case... Zip would be better suited:
long[] f = new long[4]{1,10,100,1000};
long[] result = f.Skip(1).Zip(f, (a, b) => a / b);
EDIT: if you're on .NET 3.5, you can easily write a Zip
extension method yourself:
public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TSecond, TResult> selector)
{
if (first == null)
throw new ArgumentNullException("first");
if (second == null)
throw new ArgumentNullException("second");
if (selector == null)
throw new ArgumentNullException("selector");
return first.ZipIterator(second, selector);
}
private static IEnumerable<TResult> ZipIterator<TFirst, TSecond, TResult>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TSecond, TResult> selector)
{
using (var enum1 = first.GetEnumerator())
using (var enum2 = second.GetEnumerator())
{
while (enum1.MoveNext() && enum2.MoveNext())
{
yield return selector(enum1.Current, enum2.Current);
}
}
}
Upvotes: 4
Reputation: 5658
Simple solution without using Linq:
IEnumerable<long> GetResults(long[] input)
{
for (int i = input.Length -1; i >= 1; --i)
yield return input[i] / input[i - 1];
}
You can use Linq on the return value tough and it works in .NET 3.5 :)
Upvotes: 0