List<int> list1 = new List<int> { 1, 2, 3, 4 };
List<int> list2 = new List<int> { 1, 1, 1, 1 };
double result = list1.Zip(list2, (a, b) => a - b).Average();
The result is 1.5 when I started it.
Just because I liked it and it appeared in one of the other comments, here is my implementation Zipthat can work in C # 3.5.
public static IEnumerable<T> Zip<T>(this IEnumerable<T> first
, IEnumerable<T> second, Func<T, T, T> resultSelector)
{
if (first == null)
throw new ArgumentNullException("first");
if (second == null)
throw new ArgumentNullException("second");
if (resultSelector == null)
throw new ArgumentNullException("resultSelector");
return ZipImpl(first, second, resultSelector);
}
public static IEnumerable<T> ZipImpl<T>(IEnumerable<T> first
, IEnumerable<T> second, Func<T, T, T> resultSelector)
{
IEnumerator<T> firstIterator = first.GetEnumerator();
IEnumerator<T> secondIterator = second.GetEnumerator();
while (firstIterator.MoveNext() && secondIterator.MoveNext())
{
yield return resultSelector(firstIterator.Current, secondIterator.Current);
}
}
Servy source
share