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
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
Existing answers already show how to add your own indexers.
, , SortedList<,>, Dictionary<,>, .
SortedList<,>
Dictionary<,>
, , , Collection<> List<>. , IList/IList<T>, ( ):
Collection<>
List<>
IList
IList<T>
public SomeType this[int someId] {...}
, , IList[<T>] .
IList[<T>]
.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); } }
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>.
List<T>
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.
Source: https://habr.com/ru/post/1699704/More articles:https://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1699699/does-windows-xp-use-the-ntfs-filesystem-function-calls-to-read-fromwrite-to-a-pagefile-pagefilesys&usg=ALkJrhgQCrl2Bauozyn4qOHf6FukNXlpAwModifying a database at run-time Grails application - databaseGoogle App Engine Application Code Optimization - optimizationViews of Maven, Hudson and Dynamic Clearcase - clearcaseFinding a strong building management system - build-processHow to link one table with many different tables? - databaseInclude ib_logfiles in backup? - mysqlASP.NET MVC Beta 1 - Does It Support Strongly Typed Data? - c #Changing java lookandfeel without changing application - javaWhat are the key factors for successful scalability of ASP.NET applications? - designAll Articles