SortedList<string, int> list = new SortedList<string, int>;
list.Add("abc", 2);
list.Add("def", 3);
string index = list.GetIndex(2) ???????
Console.WriteLine(index);
我真的很困惑。如何使用索引的值
获取数组的索引输出应为
ABC
解决方案:
使用SortedList公开的IndexOfValue方法,结合Linq扩展方法ElementAt(int index),所以:
string index = list.ElementAt(list.IndexOfValue(value)).Key;//output will be abc
- O ---
这也有效
string index = list.Keys.ElementAt<string>(list.IndexOfValue(2));
答案 0 :(得分:1)
根据您的声明,输出应为abc
,我认为您真的想要text
,而不是index
。要根据商品value
获取商品的文字,只需执行以下操作:
SortedList<string, int> list = new SortedList<string, int>();
list.Add("abc", 2);
list.Add("def", 3);
string text = list.ElementAt(listz.IndexOfValue(2)).Key
Console.WriteLine(text);
答案 1 :(得分:1)
关于SortedList.GetByIndex方法的MSDN文档:
using System;
using System.Collections;
public class SamplesSortedList {
public static void Main() {
// Creates and initializes a new SortedList.
SortedList mySL = new SortedList();
mySL.Add( 1.3, "fox" );
mySL.Add( 1.4, "jumped" );
mySL.Add( 1.5, "over" );
mySL.Add( 1.2, "brown" );
mySL.Add( 1.1, "quick" );
mySL.Add( 1.0, "The" );
mySL.Add( 1.6, "the" );
mySL.Add( 1.8, "dog" );
mySL.Add( 1.7, "lazy" );
// Gets the key and the value based on the index.
int myIndex=3;
Console.WriteLine( "The key at index {0} is {1}.", myIndex, mySL.GetKey( myIndex ) );
Console.WriteLine( "The value at index {0} is {1}.", myIndex, mySL.GetByIndex( myIndex ) );
// Gets the list of keys and the list of values.
IList myKeyList = mySL.GetKeyList();
IList myValueList = mySL.GetValueList();
// Prints the keys in the first column and the values in the second column.
Console.WriteLine( "\t-KEY-\t-VALUE-" );
for ( int i = 0; i < mySL.Count; i++ )
Console.WriteLine( "\t{0}\t{1}", myKeyList[i], myValueList[i] );
}
}
/*
This code produces the following output.
The key at index 3 is 1.3.
The value at index 3 is fox.
-KEY- -VALUE-
1 The
1.1 quick
1.2 brown
1.3 fox
1.4 jumped
1.5 over
1.6 the
1.7 lazy
1.8 dog
*/
答案 2 :(得分:1)
使用IndexOfValue
曝光的SortedList
方法,结合Linq扩展方法ElementAt(int index)
,以便:
string index = list.ElementAt(list.IndexOfValue(value)).Key;//output will be abc
答案 3 :(得分:0)
使用SortedList.Values属性获取包含SortedList对象中的值的ICollection对象。
答案 4 :(得分:0)
试一试:
SortedList<string, int> list = new SortedList<string, object>();
list.Add("One", 1);
list.Add("Two", 2);
int value = (int)list.ElementAt(1).Value;
或......
int value = list.IndexOfKey("One");