﻿ 在两个列表中应用运算符的C#-idiomatic方法是什么？ - 代码日志

#### 在两个列表中应用运算符的C#-idiomatic方法是什么？

`````` a = 1, 2, 3;
b = 5, 1, 2;

c = a * b;  // c = 5, 2, 6
``````

`````` c = b>a ? b-a : 0;  // c = 4, 0, 0
``````

(我唯一要问的是c = f(a，b)。我熟悉创建列表和访问他们的元素。)

``````var c = a.Zip(b, (x, y) => x * y);
``````

``````var c = a.Zip(b, (x, y) => x > y ? x - y : 0);
``````

``````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);
}
}
``````

http://stackoverflow.com/questions/24026624/whats-the-c-idiomatic-way-for-applying-an-operator-across-two-lists