1

I have a table contains the columns Title and Info.

I would like to create an array it's index will be the Title, and actual value of the array in that index is the Info in the same row.

So if I have 3 Rows like that:

Title      Info

ABC        Hi

DEF        Sup

GHI        Hello

I would like to ask for StringArray["ABC"], and this will return "Hi".

How can I do that?

Thanks Guy

2
  • @ScottM. - He's probably unaware of the existence of a dictionary class. Instead of being combative it would probably be more beneficial to just say "Take a look at the Dictionary class." Commented Apr 17, 2012 at 15:20
  • Are your indexes guaranteed to be unique? If they aren't then a dictionary wont work for you. Commented Apr 17, 2012 at 17:56

4 Answers 4

5

You want a Dictionary<String, String>, not a string array.

var myStrings = new Dictionary<String, String>();
myStrings.Add("ABC", "Hi");
myStrings.Add("DEF", "Sup");
myStrings.Add("GHI", "Hello");

Console.WriteLine(myStrings["ABC"]);
Sign up to request clarification or add additional context in comments.

Comments

1

Arrays can only be indexed with an integer. You would have to use Dictionary<string, string>, or some other type that implements IDictionary<string, string>, or you could implement your own type with a string indexer.

Comments

1

Please refer to Dictionary for that

You can do in this way

Dictionary<string, string> Book = new Dictionary<string, string>();

Book.Add("ABC","Hi");
Book.Add("DEF","Sup");
Book.Add("GHI","Hello");

so on and so forth.

So then when you say

Book["ABC"] it will return Hi

Comments

1

You should use dictionary to implement it.

var table = new Dictionary<string,string>(
{"ABC", "Hi"},
{"DEF", "Sup"},
{"GHI", "Hello"}
);

now you can use it

var info = table["ABC"];

you should be careful an exception will be thrown if you use unexisted key

you can use TryGetValue to avoid this exception

string info;

if(!table.TryGetValue("ABC", out info))
{
  info = "default value if required";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.