Reputation: 5998
I want to know which is the most efficient way to store a set of list of strings in C#.
My goal is to store information about "properties" like Hold(object)
or Location(x,y,object)
. To do this I have a dictionary that map the property name to a "set of values".
For example, suppose I have a "location" set for the "location" property with these values
location -> ["1","2","robot1"]
["2","3","robot2"]
["2","5","key1"]
I want to perform query like
DB["location"].Contains(["1","2","robot1"])
I don't know if it is possible but it is to give you an idea of what I need. :)
I have to modify and access these data frequently so I opted for an HashSet. But I have two main options:
HashSet<string[]>
. The problem is I think that HashSet cannot find duplicates because the standard behavior is to compare arrays by reference. For the same reason I don't know a good way to solve the "check if a [a,b,c] is contained in the set" problem.HashSet<List<string>>
. But I don't need a List to store a simple set of tuple. It seems to me too much for a simple job like that.An alternative is to write my own class to store "arguments" but I don't want to do this if something exists in the standard library. :)
Thanks :)
Upvotes: 3
Views: 1656
Reputation: 16287
Use HashSet and Tuple might be a choice
HashSet<Tuple<int, int, string>> collections;
and if you prefer using all strings:
HashSet<Tuple<string, string, string>> collections;
And for equality of Tuple, you might find this MSDN link useful. No matter which form you like, you can use below example as a reference:
Tuple<string, double, int>[] scores =
{ Tuple.Create("Ed", 78.8, 8),
Tuple.Create("Abbey", 92.1, 9),
Tuple.Create("Ed", 71.2, 9),
Tuple.Create("Sam", 91.7, 8),
Tuple.Create("Ed", 71.2, 5),
Tuple.Create("Penelope", 82.9, 8),
Tuple.Create("Ed", 71.2, 9),
Tuple.Create("Judith", 84.3, 9) };
// Test each tuple object for equality with every other tuple.
for (int ctr = 0; ctr < scores.Length; ctr++)
{
var currentTuple = scores[ctr];
for (int ctr2 = ctr + 1; ctr2 < scores.Length; ctr2++)
Console.WriteLine("{0} = {1}: {2}", currentTuple, scores[ctr2],
currentTuple.Equals(scores[ctr2]));
Console.WriteLine();
}
}
Upvotes: 1
Reputation: 564931
An alternative is to write my own class to store "arguments" but I don't want to do this if something exists in the standard library. :)
This would actually be my preference. While it's a bit of work to write this up, having an actual type to hold the values provides the ability to build the equality directly into the type, and makes its usage very explicit.
In your case, you could store 2 ints and a string instead of 3 strings, etc. More importantly, the int
and string
values can be named appropriately, which in turn makes your code far more readable and understandable.
Upvotes: 3