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

时间:2014-03-21 19:27:20

标签: c#

正如您在下面的脚本中看到的,在计算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());

1 个答案:

答案 0 :(得分:0)

我会将您的值存储为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类型here