如何用另一个数组的值替换索引

本文关键字:替换 索引 数组 何用 另一个 | 更新日期: 2023-09-27 17:51:13

在下面的脚本中可以看到,计算完results.Add(dotproduct(userseq, z));后,将结果存储在一个列表中,根据值对列表进行排序,并显示排序前值的结果索引(原始索引)和值,如下所示在排序:

0  0.235
1  0.985
2  0.342
3  0.548
4  0.754
排序后

:

1  0.985
4  0.754
3  0.548
2  0.342
0  0.235

现在,我必须将排序后的索引(排序后的索引)替换为另一个值。我有一个数组(一维),我必须将排序项的索引与该数组进行比较,如果索引相同,我读取该索引的值,并将其替换为排序后已排序的索引。像

1  0.985
4  0.754
3  0.548
2  0.342
0  0.235

索引是隐式的一维数组。

0  672534
1  234523
2  567808
3  876955
4  89457

最后的结果必须是

234523  0.985
89457   0.754
876955  0.548
567808  0.342

int sc = Convert.ToInt32(txtbx_id.Text);
int n = Convert.ToInt32(txtbx_noofrecomm.Text);
//int userseq=Array.IndexOf(d, sc);
for (int yu = 0; yu <= 92161; yu++)
{
    int wer = d[yu];
    if (wer == sc)
    {
        int userseq = yu;
    }
}
var results = new List<float>(1143600);
for (int z = 0; z < 1143600; z++)
{
    results.Add(dotproduct(userseq, z));
}
var sb1 = new StringBuilder();
foreach (var resultwithindex in results.Select((r, index) => new { result = r, Index = index }).OrderByDescending(r => r.result).Take(n))
{
    sb1.AppendFormat("{0}: {1}", resultwithindex.Index, resultwithindex.result);
    sb1.AppendLine();
}
MessageBox.Show(sb1.ToString());

如何用另一个数组的值替换索引

我会将您的值存储为KeyValuePair数据类型

// Let's create the list that will store our information
// Keys will be ints, values the doubles
var myList = new List<KeyValuePair<int, double>>();
/*
Here is where you will load the values as you desire
This is up to you! Just add them as KeyValuePair objects to your list
(234523, 0.985), (89457, 0.754), (876955, 0.548), (567808, 0.342)
*/
// For example, I'll just add one:
myList.Add(new KeyValuePair<int, double>(567808, 0.342));
// Once you have created your list of desired KeyValuePairs, let's sort them.
// This will sort from high -> low as your example showed
myList.Sort((x, y) => y.Value.CompareTo(x.Value));

那么你就剩下了一个类型为KeyValuePair<int, double>的排序列表,你可以随心所欲地做。

…您可以在这里了解更多关于KeyValuePair类型的信息。