如何将2个列表传递给Parallel.ForEach?

时间:2022-05-14 11:11:13

How do I pass 2 lists into Parallel.ForEach?

如何将2个列表传递给Parallel.ForEach?

Example:

例:

List<Person> a = new List<Person>() { new Person(), new Person(), new Person() };
List<Car> b = new List<Car>() { new Car(), new Car(), new Car() };

//PSEUDO CODE
Parallel.ForEach(a, b, (person, car) => {
    //WORK ON person, WORK ON car
});  

I would prefer to avoid encapsulating Person and Car into Object container. Is this possible?

我宁愿避免将Person和Car封装到Object容器中。这可能吗?

Thanks for any help!

谢谢你的帮助!

2 个解决方案

#1


24  

If you're using .NET 4 (which you probably are) and you're trying to pair the first Person with the first Car etc, you can just use Zip:

如果你正在使用.NET 4(你可能是)并且你试图将第一个人与第一个Car等配对,你可以使用Zip:

List<Person> a = new List<Person>() { new Person(), new Person(), new Person() };
List<Car> b = new List<Car>() {} { new Car(), new Car(), new Car() };
var zipped = a.Zip(b, (person, car) => new { person, car });

Parallel.ForEach(zipped, pair => {
    Person person = pair.person;
    Car car = pair.car;
});

#2


10  

You are looking for Enumerable.Zip

您正在寻找Enumerable.Zip

#1


24  

If you're using .NET 4 (which you probably are) and you're trying to pair the first Person with the first Car etc, you can just use Zip:

如果你正在使用.NET 4(你可能是)并且你试图将第一个人与第一个Car等配对,你可以使用Zip:

List<Person> a = new List<Person>() { new Person(), new Person(), new Person() };
List<Car> b = new List<Car>() {} { new Car(), new Car(), new Car() };
var zipped = a.Zip(b, (person, car) => new { person, car });

Parallel.ForEach(zipped, pair => {
    Person person = pair.person;
    Car car = pair.car;
});

#2


10  

You are looking for Enumerable.Zip

您正在寻找Enumerable.Zip