在 Java 中,我可以将 Vector 中的值赋给 String 变量。
String str = vector1.elementAt(0).toString();
如何在 C# 中使用 List 做同样的事情?
谢谢。
最佳答案
有很多方法可以做到这一点:
假设
List<string> yourList;
然后所有下面的将元素放在位置 index
在字符串变量中:
-
string s = yourList[index];
-
string s = yourList.ToArray()[index];
-
string s = yourList.ElementAt(index);
在以上所有内容中,index
必须在 0 - (yourList.Length-1)
范围内因为 C# 中的数组索引是从零开始的。
另一方面,虽然看起来一样,但甚至无法编译:
-
string s = youList.Skip(index).Take(1);
.Take()
在这种情况下不返回 string
但是一个IEnumerable<string>
这仍然是一个集合。
关于C# 将 List<string> 中的值分配给字符串变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11932257/