首页 > 解决方案 > 返回正数组值的数组索引 - 数组是元组的一部分

问题描述

我有以下包含一个元组的列表:

List<Tuple<int, int[]>> someInfo = new List<Tuple<int, int[]>>();

现在,考虑到我的元组已经填充了合理的值,我如何提取与 int[] 中大于 0 的值对应的所有索引?

例如,假设我的元组中的 int[] 已被初始化为:

int[] values = new int[] { -5, 5, 100, -52, 6 };

那么这个特定元组中所有正值(即 5、100 和 6)的返回索引列表应该是:1、2 和 4(基于 0 的索引)。
然后我们需要对列表“someInfo”中的所有元组执行此操作。
可以将结果提取到 int[] 的列表中。

标签: c#arraysfindtuples

解决方案


您可以使用 Linq 同时选择值和索引,然后过滤掉其值不符合您的过滤条件的项目,并返回索引:

List<Tuple<int, int[]>> someInfo = new List<Tuple<int, int[]>>
{
    new Tuple<int, int[]>(1, new[] {0, -1, -2, -3, -4}),
    new Tuple<int, int[]>(1, new[] {-5, 5, 100, -52, 5}),
    new Tuple<int, int[]>(1, new[] {1, 2, 3, 4, 5})
};

List<int[]> positiveValueIndices = someInfo
    .Select(tuple => tuple.Item2
        .Select((value, index) => new {value, index})
        .Where(item => item.value > 0)
        .Select(item => item.index)
        .ToArray())
    .ToList();

推荐阅读