简体   繁体   中英

Get All elements in between two elements in Array

I have a Array in c#.

public string[] alphabet = new string[] { "A","B","C",.......}

I want to return each and every elements which between two mentioned element.

Ex:

I want to return all elements in between "A" and "D". It should return {A,B,C,D} as result.

How can I do this? Is there any build in support or Are we suppose to write our own? Please help me.

如果仅关于Alphabet数组,则可以调用循环,然后将其变量转换为char。

Try this:

alphabetList = alphabet.ToList();
string[] range = (alphabetList.GetRange(alphabetList.IndexOf("A"), alphabetList.IndexOf("D") + 1)).ToArray();
var fist = Array.IndexOf(alphabet, "A");
var second = Array.IndexOf(alphabet, "D");
var newArray = alphabet.Skip(fist).Take(second - fist + 1).ToArray();

OR

var newArray2 = alphabet.ToList().GetRange(fist, second - fist + 1).ToArray();

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