var c = a.Zip(b, (x, y) => x * y);
For more complicated after editing:
var c = a.Zip(b, (x, y) => x > y ? x - y : 0);
Note that Zip is an extension method from Enumerable that acts on IEnumerable<T> and Queryable that acts on IQueryable<T> , so itβs possible that if the lambda is the one the data provider can deal with, it can be processed like an SQL query in a database or some other way than the built-in memory in .NET.
Someone mentioned that it was new with 4.0 in the comments. It is not difficult to implement for 3.5 yourself:
public class MyExtraLinqyStuff { public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TSecond, TResult> resultSelector) { //Do null checks immediately; if(first == null) throw new ArgumentNullException("first"); if(second == null) throw new ArgumentNullException("second"); if(resultSelector == null) throw new ArgumentNullException("resultSelector"); return DoZip(first, second, resultSelector); } private static IEnumerable<TResult> DoZip<TFirst, TSecond, TResult>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TSecond, TResult> resultSelector) { using(var enF = first.GetEnumerator()) using(var enS = second.GetEnumerator()) while(enF.MoveNext() && enS.MoveNext()) yield return resultSelector(enF.Current, enS.Current); } }
For .NET2.0 or .NET3.0 you can have the same thing, but not as an extension method, which answers another question from the comments; at that time there was no idiomatic way to do such things in .NET, or at least not with strong consensus among those we coded in .NET. Some of us had methods similar to the ones described above in our toolkits (although not extension methods), but this was all the more so since we were influenced by other languages ββand libraries than anything else (for example, I did things like above, due to what I knew from C ++ STL, but that was hardly the only possible source of inspiration)
Jon Hanna Jun 03 '14 at 23:29 2014-06-03 23:29
source share