假设我们有一个包含数据的数组:
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]
使用提供的解决方案时出现错误“Delegate 'System.Func' does not take 2 arguments”:
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();
}
关于c# - 根据另一个数组中指定的索引从数组中选择元素c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15795884/