4
        var a = new Collection<string> {"a", "b", "c"};
        var b = new Collection<int> { 1, 2, 3 };

迭代产生一组结果“a1”、“b2”、“c3”的最优雅的方法是什么?

4

4 回答 4

13

这称为“压缩”或“压缩连接”两个序列。Eric Lippert描述了这个算法并提供了一个实现。

于 2009-12-02T01:06:36.297 回答
4

强大的 Bart de Smet 在这里谈论 zip 功能:

http://community.bartdesmet.net/blogs/bart/archive/2008/11/03/c-4-0-feature-focus-part-3-intermezzo-linq-s-new-zip-operator.aspx

他最优雅的解决方案利用了 select 的重载,该重载将 2 参数 Func 委托作为其参数。

a.Select((t,i)=>new{t,i});

在此示例中, i 仅表示正在处理的项目的索引。因此,您可以为这些匿名对象创建 2 个新的可枚举项并将它们加入 i。

在性能方面,我会采用更明显的屈服循环。

于 2009-12-02T01:10:10.110 回答
3

为了补充 Eric 和 Bart 的精彩文章,这里有一个使用 System.Linq 3.5 运算符的实现:

public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult> (
    this IEnumerable<TFirst> first,
    IEnumerable<TSecond> second,
    Func<TFirst, TSecond, TResult> resultSelector)
{
    return from aa in a.Select((x, i) => new { x, i })
           join bb in b.Select((y, j) => new { y, j })
             on aa.i equals bb.j
           select resultSelector(aa.x, bb.y);
}
于 2009-12-02T01:15:35.250 回答
1

您可以创建一个迭代器块来优雅地处理这个问题:

public static class Ext
{
    public static IEnumerable<string> ConcatEach(this IEnumerable a,
       IEnumerable b)
    {
        var aItor = a.GetEnumerator();
        var bItor = b.GetEnumerator();

        while (aItor.MoveNext() && bItor.MoveNext())
            yield return aItor.Current.ToString() + bItor.Current;
    }
}

优雅地称呼它 =) 为:

var a = new Collection<string> {"a", "b", "c"};
var b = new Collection<int> {1, 2, 3};
foreach(var joined in a.ConcatEach(b))
{
    Console.WriteLine(joined);
}
于 2009-12-02T01:30:31.263 回答