如何通过并行集合最优雅地迭代? [英] How to most elegantly iterate through parallel collections?

查看:85
本文介绍了如何通过并行集合最优雅地迭代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有2个并行集合,例如: List< String> 中的人名列表以及列表< Int> 以相同的顺序(以便每个集合中的任何给定的索引都指向同一个人)。

Say I have 2 parallel collections, eg: a list of people's names in a List<String> and a list of their age in a List<Int> in the same order (so that any given index in each collection refers to the same person).

通过两个集合在同一时间,并取得每个人的名字和年龄,并与它做一些事情。对于数组,这很容易用:

I want to iterate through both collections at the same time and fetch the name and age of each person and do something with it. With arrays this is easily done with:

for (int i = 0; i < names.length; i++) {
   do something with names[i] ....
   do something with ages[i].....
}

使用集合做最好的方式(在可读性和速度方面)

What would be the most elegant way (in terms of readability and speed) of doing this with collections?

推荐答案

我将创建一个新对象封装两个。抛出数组中的内容并重复该过程。

I would create a new object that encapsulates the two. Throw that in the array and iterate over that.

List<Person>

其中

public class Person {
    public string name;
    public int age;
}

这篇关于如何通过并行集合最优雅地迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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