如何在C#邮编两个以上的泛型列表结合? [英] How to combine more than two generic lists in C# Zip?

查看:154
本文介绍了如何在C#邮编两个以上的泛型列表结合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个(它可能有超过3-4通用的列表,但在这个例子中,让3)泛型列表。

I have three (it's possible to have more than 3-4 generic list, but in this example let 3) generic lists.

List<string> list1

List<string> list2

List<string> list3

所有列表有相同数目的元素(相同的计数)。

all lists have same number of elements (same counts).

我用了两个清单合并ZIP:

I used that for combining two lists with ZIP :

var result = list1.Zip(list2, (a, b) => new {
  test1 = f,
  test2 = b
}

我用了的foreach 语句,避免的foreach 每个列表,像

I used that for foreach statement, to avoid foreach each List, like

foreach(var item in result){
Console.WriteLine(item.test1 + " " + item.test2);
}

如何使用simmilary与邮政编码为三个列表?

How to use simmilary with Zip for three lists ?

感谢

修改

我要像:

List<string> list1 = new List<string>{"test", "otherTest"};

List<string> list2 = new List<string>{"item", "otherItem"};

List<string> list3 = new List<string>{"value", "otherValue"};

ZIP后(我不知道的方法),我想结果(VS2010调试模式)

after ZIP (I don't know method), I want to result (in VS2010 debug mode)

[0] { a = {"test"},
      b = {"item"},
      c = {"value"}
    }   

[1] { a = {"otherTest"},
      b = {"otherItem"},
      c = {"otherValue"}
    }  

该怎么做?

推荐答案

对我来说,最明显的方法是使用邮编两次。

The most obvious way for me would be to use Zip twice.

例如,

var results = l1.Zip(l2, (x, y) => x + y).Zip(l3, (x, y) => x + y);

将结合(添加)三种名单,LT元素; INT方式&gt; 对象

更新:

您可以定义一个行为像邮编的IEnumerable S,像这样一个新的扩展方法:

You could define a new extension method that acts like a Zip with three IEnumerables, like so:

public static class MyFunkyExtensions
{
    public static IEnumerable<TResult> ZipThree<T1, T2, T3, TResult>(
        this IEnumerable<T1> source,
        IEnumerable<T2> second,
        IEnumerable<T3> third,
        Func<T1, T2, T3, TResult> func)
    {
        using (var e1 = source.GetEnumerator())
        using (var e2 = second.GetEnumerator())
        using (var e3 = third.GetEnumerator())
        {
            while (e1.MoveNext() && e2.MoveNext() && e3.MoveNext())
                yield return func(e1.Current, e2.Current, e3.Current);
        }
    }
}

的使用(在与上述相同的上下文中)现在变为:

The usage (in the same context as above) now becomes:

var results = l1.ZipThree(l2, l3, (x, y, z) => x + y + z);

同样的,你三个列表现在可以结合:

Similarly, you three lists can now be combined with:

var results = list1.ZipThree(list2, list3, (a, b, c) => new { a, b, c });

这篇关于如何在C#邮编两个以上的泛型列表结合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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