I want to declare a generic collection of objects and be able to access them through the indexer either by a key string value or by index. How do I do this? Is there is an out of the box .Net class that doesn’t require sub-classing?
class Program
{
static void Main(string[] args)
{
System.Collections.Generic.WhatKindOfCollection<PageTab> myPageTabs
= new System.Collections.Generic.WhatKindOfCollection<PageTab>();
PageTab pageTab1 = new PageTab();
pageTab1.ID = "tab1";
myPageTabs.Add(pageTab1);
myPageTabs.Add(new PageTab("tab2"));
myPageTabs[0].label = "First Tab";
myPageTabs["tab2"].label = "Second Tab";
}
public class PageTab
{
public PageTab(string id)
{
this.ID = id;
}
public PageTab() { }
//Can I define ID to get the key property by default?
public string ID { get; set; }
public string label { get; set; }
public bool visible { get; set; }
}
}
It looks like you’re looking for something derived from System.Collections.ObjectModel.KeyedCollections.
I don’t think that the specific class you’re looking for exists in the .NET framework, so you’ll probably have to subclass it yourself.
KeyedCollection is a base class for objects where the key is part of the object. This means that when you access it with an integer index, you’ll get back the original object instead of a KeyValueCollection.
It’s been a while since I’ve used it, but I don’t remember it being too difficult.
Edit: Another code option for you. It was easier than I remember:
To use:
Or pre-LINQ:
and