i have an array of custom objects. i’d like to be able to reference this array by a particular data member, for instance myArrary["Item1"]
“Item1” is actually the value stored in the Name property of this custom type and I can write a predicate to mark the appropriate array item. However I am unclear as to how to let the array know i’d like to use this predicate to find the array item.
I’d like to just use a dictionary or hashtable or NameValuePair for this array, and get around this whole problem but it’s generated and it must remain as CustomObj[]. i’m also trying to avoid loading a dictionary from this array as it’s going to happen many times and there could be many objects in it.
For clarification
myArray[5] = new CustomObj() // easy!
myArray["ItemName"] = new CustomObj(); // how to do this?
Can the above be done? I’m really just looking for something similar to how DataRow.Columns["MyColumnName"] works
Thanks for the advice.
What you really want is an
OrderedDictionary. The version that .NET provides in System.Collections.Specialized is not generic – however there is a generic version on CodeProject that you could use. Internally, this is really just a hashtable married to a list … but it is exposed in a uniform manner.If you really want to avoid using a dictionary – you’re going to have to live with O(n) lookup performance for an item by key. In that case, stick with an array or list and just use the LINQ
Where()method to lookup a value. You can use eitherFirst()orSingle()depending on whether duplicate entries are expected.It’s easy enough to wrap this functionality into a class so that external consumers are not burdened by this knowledge, and can use simple indexers to access the data. You could then add features like memoization if you expect the same values are going to be accessed frequently. In this way you could amortize the cost of building the underlying lookup dictionary over multiple accesses.