c# - C#:在 C# 中返回数组中的选定元素
问题描述
我需要一种方法来返回一维数组中的选择元素,其中元素的位置存储在另一个数组中,如下所示:
double[] A = new double[11] { 8, 9, 8, 7, 5, 6, 4, 8, 9, 6, 5};
Int32[] C = new Int32[3] { 1, 5, 8};
double[] B = MyMethod(A, C);
它应该返回:
{9, 6, 9}
我迷失在 Linq 的 Select, Where, Take 中:-)
解决方案
使用linq,您需要做的就是Select
从Offset
数组中将这些元素投影到源数组int
的索引器中int
这是一个适用于任何类型的通用解决方案
给定
public static T[] SliceAndDice<T>(T[] source, int[] offsets)
=> offsets.Select(t => source[t]).ToArray();
用法
var a = new double[11] { 8, 9, 8, 7, 5, 6, 4, 8, 9, 6, 5 };
var b = new int[3] { 1, 5, 8 };
var results = SliceAndDice(a,b);
Console.WriteLine(string.Join(", ", results));
输出
9, 6, 9
如果你需要括号
Console.WriteLine($"{{{string.Join(", ", results)}}}");
输出
{9, 6, 9}
对于完全验证和检查的扩展方法
public static T[] SliceAndDice<T>(this T[] source, int[] offsets)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (offsets == null) throw new ArgumentNullException(nameof(offsets));
var result = new T[offsets.Length];
for (var i = 0; i < offsets.Length; i++)
{
if(offsets[i] >= source.Length)
throw new IndexOutOfRangeException("Index outside the bounds of the source array");
result[i] = source[offsets[i]];
}
return result;
}
推荐阅读
- java - 当 Java 更新到 OpenJDK 11 时,Windows 上的 Jenkins 返回不受支持的 JVM 错误
- javascript - 客户端,如何信任来自物联网设备的自签名证书?
- angular - 从选择菜单中删除空白行
- android - 在 AndroidX 中膨胀 SlidingPaneLayout 类时出错
- ruby-on-rails - 将 Rails 5.2 升级到 6.0.0 后内存泄漏
- android - 如何修复 Java (android) 中的“无法找到空闲端口”错误
- python - 从 python timeit 函数保存返回值
- wordpress - 主题幻灯片错误,解析错误 wordpress
- android - 让 TalkBack 以编程方式读取按钮内容说明
- python-3.x - 将文本文件打印为两个单独的列表