What is C#'s most effective counterpart to Delphi's TStringList?
In our Delphi application, we use a TStringList to stor开发者_如何学编程e strings and corresponding objects. For another project, I need to do something similar to this in C#, but am not sure what the most effective way of doing this is. So far I've thought of using an array list, a list, or a dictionary. Would one of these be effective at what I want to do? If not, which is a good way to go?
It depends what features of TStringList you need. There's not really a direct replacement.
A dictionary<string,object>
is unordered, and you cannot have duplicate strings. There's no Text property to set all strings at once, etc. If all that is OK with you, I'd go for that.
Otherwise, you might consider defining a little class like:
public class Item {
public string String {get;set;}
public object Object {get;set;}
}
and then use List<Item>
. That gives you an ordered list of (string,object) tuples.
If the strings are unique, go with the Dictionary<string, T>
. If they are not guaranteed to be unique, a dictionary will not be appropriate and you would want to maybe use a list of Tuple<string, T>
(C# 4) or perhaps a list of KeyValuePair<string, T>
, which would be very similar to a dictionary except obviously not guaranteeing uniqueness, and it preserves order where a dictionary would not necessarily do so.
Dictionary<string, T>> yourDictionary; // or
List<Tuple<string, T>> yourCollection; // or
List<KeyValuePair<string, T>> yourCollection;
Finally, you can define your own encapsulating type and create a list of that if you do not wish to use one of the other solutions.
This depends on the features you need for your collection. I would use Dictionary<string, object>
(generics).
this blog post show the differences between SortedList and Dictionary quite good
http://blog.bodurov.com/Performance-SortedList-SortedDictionary-Dictionary-Hashtable/
Generic version:
List<string>
Direct, non-generic (don't use!):
ArrayList
See MSDN: 1, 2
For a small list of objects I would use Dictionary<string,xxx>
where xxx
is the type of object you want to store indexed by string.
Nothing! believe me, my friend, because of the word "counterpart" I have to say Nothing!
精彩评论