首页 > 解决方案 > 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 中:-)

标签: c#

解决方案


使用linq,您需要做的就是SelectOffset数组中将这些元素投影到源数组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;
}

推荐阅读