I have implemented the "[ ]" operator in a class that I have created to return values associated with a key (the same concept of a dictionary, except that it's possible to have the same key more than one time). However, looking at my code I don't think it is as efficient as it could be.
public class MyClass
{
public object[][] Values;
public MyClass()
{
Values = new object[4][];
}
public IEnumerable<object> this[string key]
{
get
{
var results = new List<object>();
foreach (var value in this.Values)
{
if (value[0].ToString() == key)
{
results.Add(value[1]);
}
}
return results;
}
}
}
Values can contain a bunch of 2 values arrays.
A small example:
MyClass class = new MyClass();
class.Values[0] = new object[] { "key1", 25 };
class.Values[1] = new object[] { "key2", 3 };
class.Values[2] = new object[] { "key2", 789 };
class.Values[3] = new object[] { "key4", 12 };
and when I do class["key2"]
, it returns a collection containing 3
and 789
.
What do you think of the way I implemented the this[string key] method? Do you think there is a way to do this without iterating on all the objects in the Values array?
2 Answers 2
If you look for performance, you'd better rely on the framework dictionary. You can use the Dictionary<string, List<object>>
to do what you need. When you add a new key and value, look if the key already exists. If so, add the value to the array and don't add the key.
-
1\$\begingroup\$ I think you mean
Dictionary<string, List<object>>
. \$\endgroup\$svick– svick2012年07月10日 14:14:17 +00:00Commented Jul 10, 2012 at 14:14 -
\$\begingroup\$ Yes you're right. Thanks. How do I accept your edit? \$\endgroup\$Amiram Korach– Amiram Korach2012年07月10日 14:16:41 +00:00Commented Jul 10, 2012 at 14:16
-
\$\begingroup\$ I didn't propose that edit, you could have just edited your answer by yourself. (I have enough reputation on this site, so that my edits are accepted automatically. If I didn't and I made that edit, you would see a number beside the "edit" button, signifying how many people already accepted the edit.) \$\endgroup\$svick– svick2012年07月10日 15:01:24 +00:00Commented Jul 10, 2012 at 15:01
This is intended as a comment to the answer from @AmiramKorach; here is a reasonable way to get from the list you have to the dictionary you want (without concerning yourself about managing the dictionary details):
Dictionary<string, List<int>> result =
new[]
{
new {Name = "key1", Value = 25},
new {Name = "key2", Value = 3},
new {Name = "key2", Value = 789},
new {Name = "key3", Value = 12}
}
.GroupBy(p => p.Name)
.ToDictionary(
group => group.Key,
values => values.Select(g => g.Value).ToList()
);
object
. \$\endgroup\$