簡體   English   中英

根據另一個數組c#中指定的索引從數組中選擇元素

[英]Selecting elements from array according to indices specified in another array c#

假設我們有一個包含數據的數組:

double[] x = new double[N] {x_1, ..., x_N};

大小為N數組包含與x元素對應的標簽:

int[] ind = new int[N] {i_1, ..., i_N};

根據ind選擇具有特定標簽I x中所有元素的最快方法是什么?

例如,

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]

使用提供的解決方案我得到一個錯誤“委托'System.Func'不帶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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM