tags:

views:

24

answers:

3

In C#, how can I store a collection of values so if I want to retrieve a particular value later, I can do something like:

myCollection["Area1"].AreaCount = 50;

or

count = myCollection["Area1"].AreaCount;

Generic list?

I'd like to store more than one property to a "key". Is a class the answer?

+2  A: 

You're looking for the Dictionary<string, YourClass> class. (Where YourClass has an AreaCount property)

SLaks
Thank You SLaks for your always helpful answers.
0A0D
A: 

This functionality is provided by indexers

Vash
+1  A: 

EDIT
Based on your comment, it seems like you want a Dictionary (as already suggested) where your object holds all your 'values.'

For Instance:

public class MyClass
{
   public int AreaCount;
   public string foo;
   public bool bar;
}

//Create dictionary to hold, and a loop to make, objects:
Dictionary<string, MyClass> myDict = new Dictionary<string, MyClass>();
while(condition)
{ 
   string name = getName(); //To generate the string keys you want
   MyClass mC = new MyClass();
   myDict.Add(name, mC);
}

//pull out yours and modify AreaCount
myDict["Area1"].Value.AreaCount = 50;

Alternatively, you could add a string "Name" to you class (I'm using fields for the example, you'd probably use properties) and use Linq:

//Now we have a list just of your class (assume we've already got it)
myClass instanceToChange = (from items in myList
                          where Name == "Area1"
                          select item).FirstOrDefault();

myClass.AreaCount = 50;

Does that help more?

ORIGINAL RESPONSE
I'm not completely sure what you're asking, but I'll give it ago.

Given a list of Objects from which you need to grab a particular object, there are (generally) 4 ways- depending on your specific needs.

The Generic List<T> really only does this well at all if your object already supports some kind of searching (like String.Contains()).

A SortedList uses IComparer to compare and sort the Key values and arrange the list that way.

A Dictionary stores a Key and Value so that KeyValuePair objects can be retrieved.

A HashTable uses Keys and Values where the Keys must implement GetHashCode() and ObjectEquals

The specific one you need will vary based on your specific requirements.

AllenG
I'd like to store more than one property to a key. Is this possible?
0A0D
Depends on if you're in .NET 4 or not. If so, you can use a List<Tuple<TItem1, TItem2>> and treat TItem1 as your 'key.' I haven't had to use SortedList or HashTable much, so maybe someone can lay me knowledge on those, but I know you can only have value for a given key in a Dictionary. In .NET 3.5 or before, you'd probably have to write something...
AllenG
See your edit. So I populate the fields of the class and then store the class along with the key into the dictionary
0A0D
Yeah, basically. YMMV, but this should get you pretty close to what you need.
AllenG