根据在另一个数组中指定的索引从数组中选择元素
本文关键字:数组 索引 元素 选择 另一个 | 更新日期: 2023-09-27 18:07:13
假设我们有一个数据数组:
double[] x = new double[N] {x_1, ..., x_N};
和大小为N
的数组,包含与x
的元素相对应的标签:
int[] ind = new int[N] {i_1, ..., i_N};
根据ind
从x
中选出具有特定标签I
的所有元素的最快方法是什么?
x = {3, 2, 6, 2, 5}
ind = {1, 2, 1, 1, 2}
I = ind[0] = 1
结果:y = {3, 6, 2}
显然,它可以很容易地(但不是有效和干净)完成循环,但我认为应该有方法如何使用.Where
和lambdas..谢谢
MarcinJuraszek提供的答案完全正确,谢谢。然而,我简化了这个问题,希望它能在我原来的情况下起作用。如果我们有泛型,请检查一下有什么问题:
T1[] xn = new T1[N] {x_1, ..., x_N};
T2[] ind = new T2[N] {i_1, ..., i_N};
T2 I = ind[0]
使用解决方案提供了一个错误的"委托"系统。函数'不接受2个参数':
T1[] y = xn.Where((x, idx) => ind[idx] == I).ToArray();
非常感谢
怎么样:
var xs = new[] { 3, 2, 6, 2, 5 };
var ind = new[] { 1, 2, 1, 1, 2 };
var I = 1;
var results = xs.Where((x, idx) => ind[idx] == I).ToArray();
它使用第二种,不太流行的Where
重载:
Enumerable.Where<TSource>(IEnumerable<TSource>, Func<TSource, Int32, Boolean>)
有项目索引可用作为谓词参数(在我的解决方案中称为idx
)。
通用版本
public static T1[] WhereCorresponding<T1, T2>(T1[] xs, T2[] ind) where T2 : IEquatable<T2>
{
T2 I = ind[0];
return xs.Where((x, idx) => ind[idx].Equals(I)).ToArray();
}
使用static void Main(string[] args)
{
var xs = new[] { 3, 2, 6, 2, 5 };
var ind = new[] { 1, 2, 1, 1, 2 };
var results = WhereCorresponding(xs, ind);
}
通用版+ double
版本
public static T[] Test<T>(T[] xs, double[] ind)
{
double I = ind[0];
return xs.Where((x, idx) => ind[idx] == I).ToArray();
}
这是Enumerable.Zip的典型用法,它运行两个彼此并行的枚举对象。使用Zip,你可以得到你的结果与一个通过。下面是完全类型无关的,尽管我使用int
s和string
s来说明:
int[] values = { 3, 2, 6, 2, 5 };
string[] labels = { "A", "B", "A", "A", "B" };
var searchLabel = "A";
var results = labels.Zip(values, (label, value) => new { label, value })
.Where(x => x.label == searchLabel)
.Select(x => x.value);