How do I create a single list of object pairs from two lists in C#?

后端 未结 6 892
野趣味
野趣味 2020-12-07 01:25

I have two lists of objects. List A and List B. I need to create List C which combines List A and List B into pairs. For example:

List A
object a1
object a2
         


        
6条回答
  •  心在旅途
    2020-12-07 01:45

    .NET Core 3 has a new overload for the Zip method. It takes two IEnumerables and creates one IEnumerable containing value tuples with the elements from both input IEnumerables.

    IEnumerable<(A a, B b)> pairs = listA.Zip(listB);
    

    You can use the result in multiple ways:

    foreach((A a, B b) in pairs)
    {
        // Do something with a and b
    }
    
    foreach(var (a, b) in pairs)
    {
        // Do something with a and b
    }
    
    foreach(var pair in pairs)
    {
        A a = pair.a;
        B b = pair.b;
    }
    

提交回复
热议问题