如何最优雅地遍历并行集合? [英] How to most elegantly iterate through parallel collections?

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

问题描述

假设我有 2 个并行集合,例如:List 中的人名列表和 List 中的年龄列表相同的顺序(这样每个集合中的任何给定索引都指向同一个人).

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天全站免登陆