c# - 返回正数组值的数组索引 - 数组是元组的一部分
问题描述
我有以下包含一个元组的列表:
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[] 的列表中。
解决方案
您可以使用 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();
推荐阅读
- mongodb - 如何使用 mongoose 检查 mongodb 文档数组中的现有条目
- video-streaming - 我已经从 mp4 转换了 m3u8 文件。从我的服务器访问视频时未播放视频以及如何添加视频质量
- css - CSS:向滚动条添加左边距
- python - Django:无法从模板保存图像
- reactjs - React开发模式下如何检测对象热重载
- java - 如何将视频添加到媒体商店数据库?
- iis - IIS Server Windows server 2012 r2 文件删除问题
- javascript - 为什么这些变量不能保持价值?
- c++ - 在另一个方法(同一个类)上使用重载运算符(在一个类中定义)(本征用法)
- java - 与 StringBuilder 不同,回溯更改整数值