使用foreach同时迭代多个列表(语法糖)

时间:2013-08-23 06:11:44

标签: c# .net

嗨,有没有办法做这样的事情:

for (int i = 0; i < Math.Min(a.Count, b.Count); i++)
{
    // Do stuff
    //a[i]
    //b[i]
}

与Foreach?

因为写一些像

这样的东西会很好
foreach(var item1 in list1 and var item2 in list2 /* ....*/)
{
   item1.use(item2);
}

修改

好的抱歉我对某些人不够清楚,所以希望能有更好的解释

List<classA> listA = fillListA();
List<classB> listB = fillListB();
//here could be infinity many lists of sometimes diffrent T types

现在我想执行某种 ForEach ,因为我不喜欢使用 for 循环 它应该简单明了,像

foreach(var item1 in list1 and var item2 in list2 /* and ...*/)
{
    item1.use(item2);
}

AFAIK我不能修改这样一个keay词类的东西 所以我认为可以构建像Parallel.ForEach这样的迭代器ForEach<TSource>(IEnumerable<TSource>, Action<TSource>) 但是我被困了,因为我不知道如何实施它

Static.ForEach<TSource>(IEnumerable<TSource>,IEnumerable<TSource>, ???Action<TSource,???>????)

4 个答案:

答案 0 :(得分:62)

你可以做foreach幕后工作,但有两个枚举器:

using(var e1 = list1.GetEnumerator())
using(var e2 = list2.GetEnumerator())
{
    while(e1.MoveNext() && e2.MoveNext())
    {
         var item1 = e1.Current;
         var item2 = e2.Current;

         // use item1 and item2
    }
}

为方便起见,您可以编写如下所示的扩展方法:

public static void ZipDo<T1, T2>( this IEnumerable<T1> first, IEnumerable<T2> second, Action<T1, T2> action)
{
    using (var e1 = first.GetEnumerator())
    using (var e2 = second.GetEnumerator())
    {
        while (e1.MoveNext() && e2.MoveNext())
        {
            action(e1.Current, e2.Current);
        }
    }
}

并使用它:

list1.ZipDo(list2, (i1,i2) => i1.Use(i2));

顺便说一下,您可以将其展开以使用3个或更多列表:

public static void ZipDo<T1, T2, T3>(this IEnumerable<T1> first,
    IEnumerable<T2> second, IEnumerable<T3> third,
    Action<T1, T2, T3> action)
{
    using (var e1 = first.GetEnumerator())
    using (var e2 = second.GetEnumerator())
    using (var e3 = third.GetEnumerator())
    {
        while (e1.MoveNext() && e2.MoveNext() && e3.MoveNext())
        {
            action(e1.Current, e2.Current, e3.Current);
        }
    }
}

当集合具有不同的泛型类型时,需要上述方法。但是,如果它们都具有相同的泛型类型,那么您可以编写一个灵活的方法,该方法可以使用任意数量的IEnumerable<T> s:

public static void ZipAll<T>(this IEnumerable<IEnumerable<T>> all, Action<IEnumerable<T>> action)
{
    var enumerators = all.Select(e => e.GetEnumerator()).ToList();
    try
    {
        while (enumerators.All(e => e.MoveNext()))
            action(enumerators.Select(e => e.Current));
    }
    finally
    {
        foreach (var e in enumerators) 
            e.Dispose();
    }
}

并使用它:

var lists = new[] {
     new[]{ 1, 1, 1 }, 
     new[]{ 2, 2, 2 }, 
     new[]{ 3, 3, 3 }};

lists.ZipAll(nums => Console.WriteLine(nums.Sum()));
// 6
// 6
// 6

答案 1 :(得分:27)

我唯一能想到的就是Enumerable.Zip以及tuples

foreach(var tuple in list1.Zip(list2, Tuple.Create))
{
    tuple.Item1.use(tuple.Item2);
}

当然,如果不是use,我们有一个非副作用的方法,从这两个元素产生第三个值,你可以这样做:

var result = list1.Zip(list2, (item1, item2) => item1.ProduceObject(item2))
                  .ToList(); // if required

答案 2 :(得分:4)

您可以使用Zip方法(虽然仅在.net 4及以上版本中提供)吗?

List<int> l4 = new List<int> { 1, 2, 3, 4 };
List<int> l5 = new List<int> { 5, 6, 7 };

var l4Andl5 = l4.Zip(l5, (l, m) => new { List1 = l, List2 = m });
foreach (var x in l4Andl5)
{


}

答案 3 :(得分:3)

如果列表具有相同的长度,您也可以简单地使用本地整数变量:

List<classA> listA = fillListA();
List<classB> listB = fillListB();

var i = 0;
foreach(var itemA in listA)
{
    itemA.use(listB[i++]);
}