通过2列出循环一次 [英] Looping through 2 Lists at once

查看:133
本文介绍了通过2列出循环一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个名单是相同的长度,是否有可能通过这两个列表循环一次?

I have two lists that are of the same length, is it possible to loop through these two lists at once?

我要寻找正确的语法做以下

I am looking for the correct syntax to do the below

foreach itemA, itemB in ListA, ListB
{
  Console.WriteLine(itemA.ToString()+","+itemB.ToString());
}



你认为这是可能在C#中?而如果是,什么是lambda表达式相当于该

do you think this is possible in C#? And if it is, what is the lambda expression equivalent of this?

推荐答案

:澄清;这是在通用LINQ / 的IEnumerable<有用; T> 的背景下,在这里您不能使用一个索引,因为:它不存在于可枚举,和b:你不能保证你能多次读取数据了。由于OP提到lambda表达式,它发生了LINQ可能不会太遥远(是的,我当然知道,LINQ和lambda表达式是不太一样的东西)。

[edit]: to clarify; this is useful in the generic LINQ / IEnumerable<T> context, where you can't use an indexer, because a: it doesn't exist on an enumerable, and b: you can't guarantee that you can read the data more than once. Since the OP mentions lambdas, it occurs that LINQ might not be too far away (and yes, I do realise that LINQ and lambdas are not quite the same thing).

这听起来像你需要缺少邮编运营商;还可以恶搞吧:

It sounds like you need the missing Zip operator; you can spoof it:

static void Main()
{
    int[] left = { 1, 2, 3, 4, 5 };
    string[] right = { "abc", "def", "ghi", "jkl", "mno" };

    // using KeyValuePair<,> approach
    foreach (var item in left.Zip(right))
    {
        Console.WriteLine("{0}/{1}", item.Key, item.Value);
    }

    // using projection approach
    foreach (string item in left.Zip(right,
        (x,y) => string.Format("{0}/{1}", x, y)))
    {
        Console.WriteLine(item);
    }
}

// library code; written once and stuffed away in a util assembly...

// returns each pais as a KeyValuePair<,>
static IEnumerable<KeyValuePair<TLeft,TRight>> Zip<TLeft, TRight>(
    this IEnumerable<TLeft> left, IEnumerable<TRight> right)
{
    return Zip(left, right, (x, y) => new KeyValuePair<TLeft, TRight>(x, y));
}

// accepts a projection from the caller for each pair
static IEnumerable<TResult> Zip<TLeft, TRight, TResult>(
    this IEnumerable<TLeft> left, IEnumerable<TRight> right,
    Func<TLeft, TRight, TResult> selector)
{
    using(IEnumerator<TLeft> leftE = left.GetEnumerator())
    using (IEnumerator<TRight> rightE = right.GetEnumerator())
    {
        while (leftE.MoveNext() && rightE.MoveNext())
        {
            yield return selector(leftE.Current, rightE.Current);
        }
    }
}

这篇关于通过2列出循环一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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