我有两个对象列表.列表A和列表B.我需要创建列表C,将列表A和列表B组合成对.例如:
List A object a1 object a2 object a3 List B object b1 object b2 object b3 List C (creates pairs) object c1 (object a1,object b1) object c2 (object a2,object b2) object c3 (object a3,object b3)
解决方法
这样做:
public static IEnumerable<Tuple<T,U>> CombineWith<T,U>(this IEnumerable<T> first,IEnumerable<U> second) { using (var firstEnumerator = first.GetEnumerator()) using (var secondEnumerator = second.GetEnumerator()) { bool hasFirst = true; bool hasSecond = true; while ( // Only call MoveNext if it didn't fail last time. (hasFirst && (hasFirst = firstEnumerator.MoveNext())) | // WARNING: Do NOT change to ||. (hasSecond && (hasSecond = secondEnumerator.MoveNext())) ) { yield return Tuple.Create( hasFirst ? firstEnumerator.Current : default(T),hasSecond ? secondEnumerator.Current : default(U) ); } } }
编辑:我非常喜欢Paul’s的答案.