linq 如何在C# Zip中合并两个以上的泛型列表?

blpfk2vs  于 2022-12-06  发布在  C#
关注(0)|答案(8)|浏览(257)

我有三个(有可能有3-4个以上泛型列表,但在本例中是3个)泛型列表。

List<string> list1

List<string> list2

List<string> list3

所有列表具有相同数量的元素(相同计数)。
我用ZIP将两个列表组合在一起:

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

我对foreach使用了那个语句,以避免foreach的每一个List,像

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

如何使用Simmilary与Zip的三个列表?
谢谢

编辑:

我想要:

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调试模式下)

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

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

那怎么办呢?

o2g1uqev

o2g1uqev1#

对我来说,最明显的方法是使用Zip两次。
例如,

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

将合并(添加)三个List<int>对象的元素。

更新日期:

您可以定义一个新的扩展方法,其作用类似于具有三个IEnumerableZip,如下所示:

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

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

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

类似地,您的三个列表现在可以与以下内容组合:

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

cdmah0mi2#

There is another quite interesting solution that I'm aware of. It's interesting mostly from educational perspective but if one needs to perform zipping different counts of lists A LOT, then it also might be useful.
This method overrides .NET's LINQ SelectMany function which is taken by a convention when you use LINQ's query syntax. The standard SelectMany implementation does a Cartesian Product. The overrided one can do zipping instead. The actual implementation could be:

static IEnumerable<TResult> SelectMany<TSource, TCollection, TResult>(this IEnumerable<TSource> source,
        Func<TSource, IEnumerable<TCollection>> selector, Func<TSource, TCollection, TResult> select)
{
    using (var e1 = source.GetEnumerator())
        using (var e2 = selector(default(TSource)).GetEnumerator())
            while (true)
                if (e1.MoveNext() && e2.MoveNext())
                    yield return select(e1.Current, e2.Current);
                else
                    yield break;
}

It looks a bit scary but it is a logic of zipping which if written once, can be used in many places and the client's code look pretty nice - you can zip any number of IEnumerable<T> using standard LINQ query syntax:

var titles = new string[] { "Analyst", "Consultant", "Supervisor"};
var names = new string[] { "Adam", "Eve", "Michelle" };
var surnames = new string[] { "First", "Second", "Third" };

var results =
    from title in titles
    from name in names
    from surname in surnames
    select $"{ title } { name } { surname }";

If you then execute:

foreach (var result in results)
    Console.WriteLine(result);

You will get:

Analyst Adam First
Consultant Eve Second
Supervisor Michelle Third

You should keep this extension private within your class because otherwise you will radically change behavior of surrounding code. Also, a new type will be useful so that it won't colide with standard LINQ behavior for IEnumerables.
For educational purposes I've created once a small c# project with this extension method + few benefits: https://github.com/lukiasz/Zippable
Also, if you find this interesting, I strongly recommend Jon Skeet's Reimplementing LINQ to Objects articles .
Have fun!

aor9mmx1

aor9mmx13#

您可以在C#中使用级联zip方法、匿名类和元组结果合并许多列表。

List<string> list1 = new List<string> { "test", "otherTest" };
List<string> list2 = new List<string> { "item", "otherItem" };
List<string> list3 = new List<string> { "value", "otherValue" };

IEnumerable<Tuple<string, string, string>> result = list1
    .Zip(list2, (e1, e2) => new {e1, e2})
    .Zip(list3, (z1, e3) => Tuple.Create(z1.e1, z1.e2, e3));

其结果是:

[0]
{(test, item, value)}
    Item1: "test"
    Item2: "item"
    Item3: "value"
5rgfhyps

5rgfhyps4#

使用**.NET 6**

..和超过Zip的元素可以用来产生一个由三个指定序列中的元素组成的元组序列。[doc]

var titles = new string[] { "Analyst", "Consultant", "Supervisor"};
var names = new string[] { "Adam", "Eve", "Michelle" };
var surnames = new string[] { "First", "Second", "Third" };

IEnumerable<(string Title, string Name, string Surname)> zip = titles.Zip(names, surnames);
a7qyws3x

a7qyws3x5#

这是我们需要决定是否支持可读性更好的代码而不是更短的代码的情况之一。

class Program
{
    static void Main(string[] args)
    {
        List<string> list1 = new List<string> { "test", "otherTest" };
        List<string> list2 = new List<string> { "item", "otherItem" };
        List<string> list3 = new List<string> { "value", "otherValue" };

        var result = CombineListsByLayers(list1, list2, list3);
    }

    public static List<string>[] CombineListsByLayers(params List<string>[] sourceLists)
    {
        var results = new List<string>[sourceLists[0].Count];

        for (var i = 0; i < results.Length; i++)
        {
            results[i] = new List<string>();
            foreach (var sourceList in sourceLists)
                results[i].Add(sourceList[i]);
        }
        return results;
    }
nmpmafwu

nmpmafwu6#

用于压缩任意数量的不同大小列表的通用解决方案:

public static IEnumerable<TItem> ZipAll<TItem>(this IReadOnlyCollection<IEnumerable<TItem>> enumerables)
{
   var enumerators = enumerables.Select(enumerable => enumerable.GetEnumerator()).ToList();
   bool anyHit;
   do
   {
      anyHit = false;
      foreach (var enumerator in enumerators.Where(enumerator => enumerator.MoveNext()))
      {
          anyHit = true;
          yield return enumerator.Current;
      }
   } while (anyHit);

   foreach (var enumerator in enumerators)
   {
      enumerator.Dispose();
   }
}
wh6knrhe

wh6knrhe7#

您可以将这些List<string>合并为List<List<string>>并对其进行聚合

List<string> list1 = new List<string> { "test", "otherTest" };
List<string> list2 = new List<string> { "item", "otherItem" };
List<string> list3 = new List<string> { "value", "otherValue" };

var list = new List<List<string>>() { list1, list2, list3 }
    .Aggregate(
        Enumerable.Range(0, list1.Count).Select(e => new List<string>()),
        (prev, next) => prev.Zip(next, (first, second) => { first.Add(second); return first; })
    )
    .Select(e => new
    {
        a = e.ElementAt(0),
        b = e.ElementAt(1),
        c = e.ElementAt(2)
    });

测试结果

[
  {
    "a": "test",
    "b": "item",
    "c": "value"
  },
  {
    "a": "otherTest",
    "b": "otherItem",
    "c": "otherValue"
  }
]

请参阅dotnetfiddle.net

yks3o0rb

yks3o0rb8#

使用匿名元组的解决方案(我认为是. Net 4或更高版本):

List<Object1> list1;
List<Object2> list2;
List<Object3> list3;

foreach (var ((first, second), third) in list1.Zip(list2).Zip(list3))
{
   // first is an Object1
   // second is an Object2
   // third is an Object3
}

相关问题