Eri*_*bes 7 .net c# linq ienumerable
我有一个IEnumerable<T>和IEnumerable<U>我想要合并到IEnumerable<KeyValuePair<T,U>>KeyValuePair中连接在一起的元素的索引是相同的.注意我没有使用IList,所以我没有计算我正在合并的项目或索引.我怎样才能做到最好?我更喜欢LINQ的答案,但任何以优雅的方式完成工作的东西都会起作用.
Mau*_*fer 17
注意:从.NET 4.0开始,该框架.Zip在IEnumerable中包含一个扩展方法,在此处记录.以下内容适用于后代,适用于早于4.0的.NET framework版本.
我使用这些扩展方法:
// From http://community.bartdesmet.net/blogs/bart/archive/2008/11/03/c-4-0-feature-focus-part-3-intermezzo-linq-s-new-zip-operator.aspx
public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TSecond, TResult> func) {
if (first == null)
throw new ArgumentNullException("first");
if (second == null)
throw new ArgumentNullException("second");
if (func == null)
throw new ArgumentNullException("func");
using (var ie1 = first.GetEnumerator())
using (var ie2 = second.GetEnumerator())
while (ie1.MoveNext() && ie2.MoveNext())
yield return func(ie1.Current, ie2.Current);
}
public static IEnumerable<KeyValuePair<T, R>> Zip<T, R>(this IEnumerable<T> first, IEnumerable<R> second) {
return first.Zip(second, (f, s) => new KeyValuePair<T, R>(f, s));
}
Run Code Online (Sandbox Code Playgroud)
编辑:在评论之后,我不得不澄清并解决一些问题:
Las*_*olt 16
作为对这个问题绊脚石的任何人的更新,.Net 4.0本身支持这个来自MS:
int[] numbers = { 1, 2, 3, 4 };
string[] words = { "one", "two", "three" };
var numbersAndWords = numbers.Zip(words, (first, second) => first + " " + second);
Run Code Online (Sandbox Code Playgroud)