C# `SortedList.IndexOfValue()`: Finding the Index of a Value in a SortedList

Learn how to efficiently find the index of a specific value within a C# `SortedList` using the `IndexOfValue()` method. This tutorial explains its functionality, search mechanism, return values, and time complexity, providing practical examples for data retrieval and manipulation.



Using C#'s `SortedList.IndexOfValue()` Method

The C# `SortedList.IndexOfValue()` method finds the index of the first occurrence of a specified value within a `SortedList` object. A `SortedList` stores key-value pairs in sorted order based on the keys.

Understanding `SortedList.IndexOfValue()`

The `IndexOfValue()` method searches the `SortedList`'s values for the first match of the given value. It uses the default equality comparer for the value type. The search is linear, meaning it iterates through the values until a match is found or the end of the list is reached.

`IndexOfValue()` Syntax


public int IndexOfValue(object value);

The method takes the value to search for (`value`) as input and returns an integer. The index (zero-based) of the first occurrence of the value is returned. If the value isn't found, it returns -1. Note that this method uses a linear search, resulting in O(n) time complexity (where n is the number of elements).

Example 1: Finding the Index of a String Value


using System;
using System.Collections;

public class IndexOfValueExample {
    public static void Main(string[] args) {
        SortedList myList = new SortedList();
        // ... (code to populate the SortedList) ...
        // ... (code to find and print the index of a specific value) ...
    }
}

Example 2: Finding the Index of a Custom Object


using System;
using System.Collections;

// ... (Person class definition) ...

public class IndexOfValueExample {
    public static void Main(string[] args) {
        SortedList myList = new SortedList();
        // ... (code to populate the SortedList with Person objects) ...
        int index = myList.IndexOfValue(new Person("Alice", 30)); //Finds index of Person object with Age=30
        Console.WriteLine($"Index: {index}");
    }
}