3

In Java, I can assign a value from Vector to a String variable.

String str = vector1.elementAt(0).toString();

How can I do the same thing in C# with List?

Thanks.

1
  • 2
    string s = myList[0].ToString() if it isn't a string, string s = myList[0] if myList = new List<string>();. Commented Aug 13, 2012 at 10:17

5 Answers 5

3

There are many ways to do this:

Assuming

List<string> yourList;

Then all of the following would put the element in position index inside a string variable:

  1. string s = yourList[index];
  2. string s = yourList.ToArray()[index];
  3. string s = yourList.ElementAt(index);

In all of the above, index must fall within the range 0 - (yourList.Length-1) since array indexing in C# is zero-based.

This, on the other hand, while it would seem the same, won't even compile:

  1. string s = youList.Skip(index).Take(1);

.Take() in this case doesn't return a string but a IEnumerable<string> which is still a collection.

Sign up to request clarification or add additional context in comments.

Comments

3
List<string> list = ...
...
string str = list[0];
...

Comments

3

You can use index with the list.

List<string> list = new List<string>();
string str = list[0];

Comments

1

String str = vector1[0].ToString();

Comments

0
//Creating a list of strings
List<string> lst = new List<string>();
...
//The string is filled with values, i is an int
string ithValue = lst[i];

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.