TheSwamp
Code Red => .NET => Topic started by: TR on March 10, 2007, 02:04:25 PM
-
In boo I can create a dictionary to map objects to keywords. For example I can create a dictionary like the one below to groups lists of employees.
employees = {'engineers':['dave', 'charlie', 'michael', 'doug'], 'drafters':['gary', 'fredrico', 'jim', 'rich'], 'salesmen':['jim', 'eric', 'george', 'kerry']}
for user in employee['drafters']:
print user
Returns:
gary
fredrico
jim
rich
For brevity sake I mapped them to lists of strings, but I could have used class instances or whatever. Is there an easy way to do something like this in C#?
-
Here's one way:
// .NET 1.x
#using System.Collections;
public class MyClass
{
public void Test()
{
Hashtable employees = new Hashtable();
ArrayList drafters = new ArrayList(new string[] {"Dave", "Charlie", "Ed"});
ArrayList engineers = new ArrayList(new string[] {"John", "Paul", "George", "Ringo"});
ArrayList clerks = new ArrayList(new string[] {"Jane", "Sue"});
employees["drafters"] = drafters;
employees["engineers"] = engineers;
employees["clerks"] = clerks;
foreach( string name in employees["engineers"] )
Console.WriteLine(name);
}
}
// .NET 2.0
#using System.Collections.Generic;
public class MyClass
{
public void Test()
{
Dictionary<string, List<string>> employees = new Dictionary<string, List<string>>();
List<string> drafters = new List<string>(new string[] {"Dave", "Charlie", "Ed"});
List<string> engineers = new List<string>(new string[] {"John", "Paul", "George", "Ringo"});
List<string> clerks = new List<string>(new string[] {"Jane", "Sue"});
employees["drafters"] = drafters;
employees["engineers"] = engineers;
employees["clerks"] = clerks;
// dump one Dictionary entry's contents:
foreach( string name in employees["engineers"] )
Console.WriteLine(name);
// dump all Dictionary entries:
foreach( KeyValuePair<string, List<string>> category in employees )
{
Console.WriteLine("Category {0}", category.Key);
foreach( string name in category.Value )
Console.WriteLine(name);
}
}
}
You could also use a StringDictionary as well, in
either version.
In boo I can create a dictionary to map objects to keywords. For example I can create a dictionary like the one below to groups lists of employees.
employees = {'engineers':['dave', 'charlie', 'michael', 'doug'], 'drafters':['gary', 'fredrico', 'jim', 'rich'], 'salesmen':['jim', 'eric', 'george', 'kerry']}
for user in employee['drafters']:
print user
Returns:
gary
fredrico
jim
rich
For brevity sake I mapped them to lists of strings, but I could have used class instances or whatever. Is there an easy way to do something like this in C#?