C# equivalent for java arraylist supporting get, set and remove certain Index

一世执手 提交于 2019-12-30 04:01:05

问题


I am a Java programmer, I have used a Java ArrayList before and now I want to have something like that in C#. Some of options I need are in this Java code:

String[] strs = new String[]{"str1" , "str2" , "str3" , "str4"};
ArrayList arrayList = new ArrayList(35);
arrayList.add(strs[0]);
arrayList.add(strs[1]);
arrayList.remove(0);
arrayList.set(0, strs[2]);
String s = (String) arrayList.get(1);

I used C# ArrayList and LinkedList, but they don't have these simple options that I need. Is there another option in C# supporting accessing objects with indexes, inserting and removing from certain index?


回答1:


use List <T>

 String[] strs = new String[]{"str1" , "str2" , "str3" , "str4"};
 List<string> stringList = new List<string>();
 stringList.add(strs[0]);
 stringList.add(strs[1]);
 stringList.RemoveAt(indexYouWantToDelete)     
 String s = stringList[0];

ArrayLists in c# come from the pre-generic era tho. Since C# 2.0 we have generic collections, List <T> being one example of that. As the comment on this answer says, if you use an ArrayList, the elements that you put into the arraylist will have to be boxed (to Object, because thats the only thing an ArrayList takes as input). If you want to access them after that, they will have to be explicitly unboxed, like what you did in your question. ( --> String s = (String) arrayList.get(1); )

using generic collections (like List <T>), there is no boxing anymore, as the compiler knows what datatype the list will consist of. In this case, Strings. You could also have a List<int>, List<char>, or List<whatever>, and you can use the same indexing functionality on them.




回答2:


Use List<T> ...........................................

which has Add Remove, RemoveAt indexers like list[i] etc.



来源:https://stackoverflow.com/questions/12342637/c-sharp-equivalent-for-java-arraylist-supporting-get-set-and-remove-certain-ind

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!