简体   繁体   中英

Retrieve and Remove elements from string

Say I have a list of string

List<string> lst=new List<string>(new string[]{"a","b","c","d"}); 

I wish to get element from index 0 to index 2 assign it to another List lst1(ie the element of lst is {"a","b"} ), then remove it from lst (ie lst becomes {"c","d"} , what's the quickest way of doing this? I am thinking is there any command like

List<string> lst=new List<string>();
lst1=lst.getElements(1,2);
lst.remove(1,2);

Use GetRange() to copy of a range of elements and RemoveRange() to removes a range of elements.

Example :

List<string> lst = new List<string>(new string[] { "a", "b", "c", "d" });
List<string> lst1 = lst.GetRange(0, 2);
lst.RemoveRange(0, 2);

Good Luck !!

You can use AddRange and RemoveRange :

var range = lst.Take(2);
lst1.AddRange(range);
lst.RemoveRange(0, 2);

Demo: http://ideone.com/1X2cV

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM