简体   繁体   中英

C# element-wise difference between two lists of numbers

Assume

List<int> diff(List<int> a, List<int> b)
{ 
    // assume same length lists
    List<int> diff= new List<int>(a.Count);
    for (int i=0; i<diff.Count; ++i)
    {
        diff[i] = a[i] - b[i];
    }
    return diff;
}

I would like to have some kind of one-liner do the same, or something that uses a lambda, rather than re-writing all the boilerplate.

for instance, in python, this would be either

[ai-bi for ai,bi in zip(a,b)]

or even

np.array(a) - np.array(b)

Is there a nice way to write this in C#? All my searches find ways to remove or add list elements, but nothing about element-wise actions.

Linq has a Zip method as well:

var diff = a.Zip(b, (ai, bi) => ai - bi);

Note that one potential bug in your code is if b has fewer elements than a then you'd get an exception when you try to access an element outside the range of b . Zip will only return items as long as both collections have items, which is effectively the shorter of the two collection lengths.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM