我如何合并(或zip)二IEnumerables在一起吗? [英] How do I merge (or zip) two IEnumerables together?

查看:525
本文介绍了我如何合并(或zip)二IEnumerables在一起吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个的IEnumerable< T> 的IEnumerable< U> 我想要合并到一个的IEnumerable< KeyValuePair< T,U>> 这些元素的指标结合在一起,在KeyValuePair是相同的。请注意,我没有使用的IList,所以我没有计数或索引,我合并的项目。我如何最好地做到这一点?我想preFER LINQ的答案,但任何获得优雅的方式做的工作也行。

I have an IEnumerable<T> and an IEnumerable<U> that I want merged into an IEnumerable<KeyValuePair<T,U>> where the indexes of the elements joined together in the KeyValuePair are the same. Note I'm not using IList, so I don't have a count or an index for the items I'm merging. How best can I accomplish this? I would prefer a LINQ answer, but anything that gets the job done in an elegant fashion would work as well.

推荐答案

注意:作为.NET 4.0,该框架包括 .ZIP 此处上的IEnumerable,记录扩展方法。以下是保持后人并为.NET framework版本,使用早于4.0。

Note: As of .NET 4.0, the framework includes a .Zip extension method on IEnumerable, documented here. The following is maintained for posterity and for use in .NET framework version earlier than 4.0.

我使用这些扩展方法:

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

修改:以后我有义务的意见,以澄清和解决一些事情:

EDIT: after the comments I'm obliged to clarify and fix some things:

  • I originally took the first Zip implementation verbatim from Bart De Smet's blog
  • Added enumerator disposing (which was also noted on Bart's original post)
  • Added null parameter checking (also discussed in Bart's post)

这篇关于我如何合并(或zip)二IEnumerables在一起吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆