Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to store pairs of strings, make an object or use a class in .NET?

Don't know whether I'm having a "thick day" - but I just wondered what is the best route here.

Context:

I have a list of fields and I want to store alias names with them (I'm using .NET 2.0 BTW) e.g.

enter image description here

So its essentially a pair of strings:

REFERENCE, Ref

COMMUNITY, Community

POST_CODE, Zip Code

... and I'm thinking it seems overboard all the time to keep creating objects for things like this, so should I create a StringDictionary and store the values that way, even though I would not use any of the functionality of the StringDictionary class and I'm not bothered about a key value pair association etc - I just want to keep a pair of strings essentially.

Any help/pointers would be great.

like image 533
Vidar Avatar asked Aug 17 '11 15:08

Vidar


People also ask

Is string a class in C#?

In C#, string is an object of System. String class that represent sequence of characters. We can perform many operations on strings such as concatenation, comparision, getting substring, search, trim, replacement etc.

Which is the base class for string () method in C#?

The String class is defined in the . NET base class library. In other words, a String object is a sequential collection of System. Char objects which represent a string.

How do you use key value pairs?

When working with serialized data, you must specify the characters that separate values within and between the key-value pairs. Elements in key-value pairs are defined as follows: Key: A unique identifier in the key-value pair. Value delimiter: Separates individual key-value pairs.


2 Answers

The "pair" generic class for .NET is Tuple. You would use it like:

var strings=new List<Tuple<string, string>>(); strings.Add(Tuple.Create("REFERENCE", "Ref")); 

A dictionary is a perfectly acceptable substitute if the left-most string is unique (ie a key). You'll get errors otherwise.

As to whether it's better to use the built-in collections or create an actual object, depends on your needs (will you be adding more columns later on? you can't do that with a dictionary approach), how often you use it (if it's a core type, you should probably make a domain model for it) etc.

Edit: As to not using any dictionary built-in functionality, that's not true: you're using its binary search algorithm and internal tree construction for lightning-fast look-ups. A list of either Tuple or your own type most likely won't have this and it will revert to a linear search.

like image 117
Blindy Avatar answered Oct 04 '22 04:10

Blindy


How about System.Tuple?

like image 24
Andy Johnson Avatar answered Oct 04 '22 04:10

Andy Johnson