根据另一个数组c#中指定的索引从数组中选择元素

Ole*_*ikh 9 c# linq arrays lambda select

假设我们有一个包含数据的数组:

double[] x = new double[N] {x_1, ..., x_N};
Run Code Online (Sandbox Code Playgroud)

N包含与以下元素对应的标签的大小数组x:

int[] ind = new int[N] {i_1, ..., i_N};
Run Code Online (Sandbox Code Playgroud)

什么是选择从所有元素最快的方法x是有一定的标签I根据ind

例如,

x = {3, 2, 6, 2, 5}
ind = {1, 2, 1, 1, 2}
I = ind[0] = 1
Run Code Online (Sandbox Code Playgroud)

结果:

y = {3, 6, 2}
Run Code Online (Sandbox Code Playgroud)

显然,使用循环可以很容易地(但不是有效和干净)完成,但我认为应该有如何使用.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]
Run Code Online (Sandbox Code Playgroud)

使用提供的解决方案我得到一个错误"委托'System.Func'不带2个参数":

T1[] y = xn.Where((x, idx) => ind[idx] == I).ToArray();
Run Code Online (Sandbox Code Playgroud)

非常感谢你

Mar*_*zek 17

那个怎么样:

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();
Run Code Online (Sandbox Code Playgroud)

它使用第二个不太流行的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();
}
Run Code Online (Sandbox Code Playgroud)

用法

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);
}
Run Code Online (Sandbox Code Playgroud)

通用+ double版本

public static T[] Test<T>(T[] xs, double[] ind)
{
    double I = ind[0];

    return xs.Where((x, idx) => ind[idx] == I).ToArray();
}
Run Code Online (Sandbox Code Playgroud)


Jos*_*nig 5

这是Enumerable.Zip的经典用法,它通过两个相互平行的枚举运行.使用Zip,您可以一次性获得结果.以下是完全类型不可知的,虽然我用ints和strings来说明:

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);
Run Code Online (Sandbox Code Playgroud)