Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6830595
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T22:38:11+00:00 2026-05-26T22:38:11+00:00

What is the .NET C# syntax for an ObservableCollection with an indexer? I would

  • 0

What is the .NET C# syntax for an ObservableCollection with an indexer? I would like an ObservableColletion and refer to the items by ordinal position or a string name. I know you the use this to denote an indexer but I don’t know how to put that in an ObservableCollection. Thanks

Thanks for the 4 answers. I know how create and ObservableCollection and I know how to create an indexer. I don’t know how to combine them. I am asking for sample code for an ObservableCollection with an ordinal and string index.
Thank again

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T22:38:11+00:00Added an answer on May 26, 2026 at 10:38 pm

    ObservableCollection inherits from Collection, so it already has position-based indexing.

    For string-based indexing, you can look into peoples implementations of ObservableDictionary.

    Personally, for better performance, I’ve created a HashedObservableCollection deriving from ObservableCollection which contains a Dictionary of keys to indexes to speed lookup time. By overriding InsertItem, RemoveItem, and ClearItems, you keep the dictionary in sync.

    In my example, the keys can be of any type but we assume the key never changes – if an item is replaced, it is replaced with an object with the same key. If you want to simplify this, you can replace TKey with String.

    Code:

    using System;
    using System.Linq;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    
    namespace foson.Utils
    {
        /// <summary>
        /// Represents BindableCollection indexed by a dictionary to improve lookup/replace performance.
        /// </summary>
        /// <remarks>
        /// Assumes that the key will not change and is unique for each element in the collection.
        /// Collection is not thread-safe, so calls should be made single-threaded.
        /// </remarks>
        /// <typeparam name="TValue">The type of elements contained in the BindableCollection</typeparam>
        /// <typeparam name="TKey">The type of the indexing key</typeparam>
        public class HashedBindableCollection<TValue, TKey> : ObservableCollection<TValue>
        {
    
            protected internal Dictionary<TKey, int> indecies = new Dictionary<TKey, int>();
            protected internal Func<TValue, TKey> _keySelector;
    
            /// <summary>
            /// Create new HashedBindableCollection
            /// </summary>
            /// <param name="keySelector">Selector function to create key from value</param>
            public HashedBindableCollection(Func<TValue, TKey> keySelector)
                : base()
            {
                if (keySelector == null) throw new ArgumentException("keySelector");
                _keySelector = keySelector;
            }
    
            #region Protected Methods
            protected override void InsertItem(int index, TValue item)
            {
                var key = _keySelector(item);
                if (indecies.ContainsKey(key))
                    throw new DuplicateKeyException(key.ToString());
    
                if (index != this.Count)
                {
                    foreach (var k in indecies.Keys.Where(k => indecies[k] >= index).ToList())
                    {
                        indecies[k]++;
                    }
                }
    
                base.InsertItem(index, item);
                indecies[key] = index;
    
            }
    
            protected override void ClearItems()
            {
                base.ClearItems();
                indecies.Clear();
            }
    
    
            protected override void RemoveItem(int index)
            {
                var item = this[index];
                var key = _keySelector(item);
    
                base.RemoveItem(index);
    
                indecies.Remove(key);
    
                foreach (var k in indecies.Keys.Where(k => indecies[k] > index).ToList())
                {
                    indecies[k]--;
                }
            }
            #endregion
    
            public virtual bool ContainsKey(TKey key)
            {
                return indecies.ContainsKey(key);
            }
    
            /// <summary>
            /// Gets or sets the element with the specified key.  If setting a new value, new value must have same key.
            /// </summary>
            /// <param name="key">Key of element to replace</param>
            /// <returns></returns>
            public virtual TValue this[TKey key]
            {
    
                get { return this[indecies[key]]; }
                set
                {
                    //confirm key matches
                    if (!_keySelector(value).Equals(key))
                        throw new InvalidOperationException("Key of new value does not match");
    
                    if (!indecies.ContainsKey(key))
                    {
                        this.Add(value);
                    }
                    else
                    {
                        this[indecies[key]] = value;
                    }
                }
            }
    
            /// <summary>
            /// Replaces element at given key with new value.  New value must have same key.
            /// </summary>
            /// <param name="key">Key of element to replace</param>
            /// <param name="value">New value</param>
            /// 
            /// <exception cref="InvalidOperationException"></exception>
            /// <returns>False if key not found</returns>
            public virtual bool Replace(TKey key, TValue value)
            {
                if (!indecies.ContainsKey(key)) return false;
                //confirm key matches
                if (!_keySelector(value).Equals(key))
                    throw new InvalidOperationException("Key of new value does not match");
    
                this[indecies[key]] = value;
                return true;
    
            }
    
            public virtual bool Remove(TKey key)
            {
                if (!indecies.ContainsKey(key)) return false;
    
                this.RemoveAt(indecies[key]);
                return true;
    
            }
    
        }
        public class DuplicateKeyException : Exception
        {
    
            public string Key { get; private set; }
            public DuplicateKeyException(string key)
                : base("Attempted to insert duplicate key " + key + " in collection")
            {
                Key = key;
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'd like to use the expression-based syntax for ASP.NET MVC's Html.BeginForm (e.g. Html.BeginForm<HomeController>(a =>
I have a syntax highlighting function in vb.net. I use regular expressions to match
Does anyone know if there's any particular reason that VB.NET construct syntax isn't consistent?
In a Asp Net data bound control one can use the nice Eval() syntax:
work on asp.net vs05. i know how to show popup ,in my below syntax
In ASP.NET 4.0 should I use new syntax <%: expression %> or 2.0 <%=
Is the syntax for VBScript and VB.NET exactly the same? Specifically, would a syntax
In a batch-file I use the following syntax to map a network drive: NET
I need to build a Regex (.NET syntax) to determine if a string ends
In .NET Framework, there are some classes which use SomethingCollection syntax. For example, when

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.