0

I needed a dictionary which keys are retrieved from the property Name of the values. E.g., the key wasn't part of the dictionary itself, it was a part of the stored values. But accessing these items with the []-indexing operator was required.

I created some classes manually to do this, my question is if there's not already a .NET class providing this functionality, since I can't believe noone needed this before.

I manually created the following things to solve this request:

A class NameTable which implemented IEnumerable<T>, IList, IList<T> where T : INameItem. Internally this class used a simple List<T> to hold the values.

An interface INameItem then just provided a property with the name Name of the type string.

Now I created an []-indexer operator in the class like this to go through all items in the internal List<T> (I know there are some better LINQ methods to do this with less code, but I prefer custom iterations over LINQ since I'm old-school):

public T this[string name]
{
    get
    {
        foreach (T content in _items)
        {
            if (content.Name == name)
            {
                return content;
            }
        }
        return null;
    }
    set
    {
        for (int i = 0; i < _items.Count; i++)
        {
            T content = _items[i];
            if (content.Name == name)
            {
                _items[i] = value;
                break;
            }
        }
    }
}
4

0 回答 0