How to go through 2 vectors in paralle using the same linq statement

I have two lists of double values ​​that are the same length.

Is it possible to go through both lists using the select statement and return the average value of the difference between the elements from the same position?

Example: {1 2 3 4}

{1 1 1 1}

I want to return ( (1 - 1) + (2 - 1) + (3 - 1) + (4 - 1) ) / 4 = 6 / 4 = 1.5

+3
source share
4 answers

Try

listA.Zip(listB, (a, b) => a - b).Average();

Without .NET 4.0 and Zip, try

listA.Select((n, index) => n - listB[index]).Average()
+3
source
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);
    }
}
+3
source

, ( Zip) , :

var arr1 = new[] {1, 2, 3, 4};
var arr2 = new[] {1, 1, 1, 1};
var res = (arr1.Sum() - arr2.Sum())/(double) arr1.Length;
+2

Using Enumerable.Rangeto generate indexes does this (if you don't have .NET 4.0 Zip)

var l1 = new List<int> { 1, 2, 3, 4 };
var l2 = new List<int> { 1, 1, 1, 1 };
double result = Enumerable.Range(0, l1.Count)
    .Select(i => l1[i] - l2[i])
    .Average();
0
source

All Articles