从自定义值索引数组获取数组's索引

本文关键字:索引 数组 获取 自定义 | 更新日期: 2023-09-27 18:06:27

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));

从自定义值索引数组获取数组's索引

使用SortedList暴露的IndexOfValue方法,结合Linq扩展方法ElementAt(int index),因此:

string index = list.ElementAt(list.IndexOfValue(value)).Key;//output will be abc

MSDN关于SortedList的文档。GetByIndex方法:

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
*/ 

根据您的声明,输出应该是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); 

使用SortedList。Values属性获取包含SortedList对象中的值的iccollection对象。

试一试:

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");