Built-in list that can be accessed by index and key

Is it possible to create a list that can be accessed either using the index or using the key?

I am looking for a type of collection that already exists but has this object, I want to avoid overriding indexers

+3
source share
5 answers

System.Collections.Specialized.NameValueCollection can do this, but it can only store strings as values.

    System.Collections.Specialized.NameValueCollection k = 
        new System.Collections.Specialized.NameValueCollection();

    k.Add("B", "Brown");
    k.Add("G", "Green");

    Console.WriteLine(k[0]);    // Writes Brown
    Console.WriteLine(k["G"]);  // Writes Green
+2
source

Existing answers already show how to add your own indexers.

, , SortedList<,>, Dictionary<,>, .

, , , Collection<> List<>. , IList/IList<T>, ( ):

public SomeType this[int someId] {...}

, , IList[<T>] .

+4

.NET ?.

KeyedCollection:

class IndexableDictionary<TKey, TItem> : KeyedCollection<TKey, TItem>
 { Dictionary<TItem, TKey> keys = new Dictionary<TItem, TKey>();

   protected override TKey GetKeyForItem(TItem item) { return keys[item];}

   public void Add(TKey key, TItem item) 
    { keys[item] = key;
      this.Add(item);
    }
 }
+2
source
public object this[int index]
{
    get { ... }
    set { ... }
}

As with an integer index, you can provide a key of any other type that you like

public object this[String key]
{
    get { ... }
    set { ... }
}

If you do not want to define your own collection, simply inherit it from List<T>or simply use a type variable List<T>.

+1
source

You can add an indexer by adding the following property to your collection:

public object this[int index]
{
    get { /* return the specified index here */ }
    set { /* set the specified index to value here */ }
}

This can be quickly added to Visual Studio by typing the index and pressing [tab] [tab].

The return type and indexer type are subject to change. You can also add several types of indexers.

0
source

Source: https://habr.com/ru/post/1699704/


All Articles