Greg
Greg

Reputation:

Return first element in SortedList in C#

I have a SortedList in C# and I want to return the first element of the list. I tried using the "First" function but it didnt really work.

Can someone please tell me how to do it?

Upvotes: 5

Views: 21147

Answers (3)

Gordon Bell
Gordon Bell

Reputation: 13643

For both SortedList and SortedList<T>, you can index the Values property:

SortedList listX = new SortedList();
    
listX.Add("B", "B");
listX.Add("A", "A");

MessageBox.Show(listX.Values[0]);

Upvotes: 10

Jorge C&#243;rdoba
Jorge C&#243;rdoba

Reputation: 52143

For a non-generic SortedList, use GetByIndex:

if (list.Count > 0)
  return list.GetByIndex(0);

Upvotes: 5

BlueTrin
BlueTrin

Reputation: 10113

Gordon Bell replied, but in the case you need to get the first key as well.

For the non generic collection:

        SortedList tmp2 = new SortedList();
        tmp2.Add("temp", true);
        tmp2.Add("a", false);
        Object mykey = tmp2.GetKey(0);
        Object myvalue = tmp2.GetByIndex(0);

For the generic collection:

        SortedList<String, Boolean> tmp = new SortedList<String, Boolean>();
        tmp.Add("temp", true);
        tmp.Add("a", false);

        String firstKey = tmp.Keys[0];
        bool firstval = tmp[firstKey];

Upvotes: 6

Related Questions