删除数组中特定字符串之前的所有值

时间:2018-02-06 18:11:38

标签: c# arrays

我有一个字符串数组:

 string[] fruits = new string[]; 

fruits可以包含这些值(大多数情况下,数组可以变大或变小。这是一个动态填充的数组)

   [0] = "Apple"
   [1] = "Banana" 
   [2] = "Orange" 
   [3] = "Cantalope" 
   [4] = "Strawberry" 
   [5] = "BlueBerry"
   [6] = "Apple"
   [7] = "Banana" 
   [8] = "Orange" 
   [9] = "Apple"
   [10] = "Banana"
   [11] = "Orange" 
   [12] = "Cantalope" 
   [13] = "Strawberry" 
   [14] = "BlueBerry"

我想知道在阵列中最后一个“Apple”之前移除所有值的最佳方法是什么。

所以数组现在看起来像:

   [0] = "Apple"
   [1] = "Banana"
   [2] = "Orange" 
   [3] = "Cantalope" 
   [4] = "Strawberry" 
   [5] = "BlueBerry"

小尝试:

            if(fruits.Contains("Apple))
            {
                List<string> fruitsList = new List<string>(fruits);

               var appleTypeIndex =  fruitsList.LastIndexOf("Apple");

            }

3 个答案:

答案 0 :(得分:3)

另一种“老式”方法是通过向后走过阵列将项目插入列表,直到你进入“Apple”,并将你的阵列重新分配给新阵列:

string[] fruits = new string[]
{
    "Apple",
    "Banana",
    "Orange",
    "Cantalope",
    "Strawberry",
    "BlueBerry",
    "Apple",
    "Banana",
    "Orange",
    "Apple",
    "Banana",
    "Orange",
    "Cantalope",
    "Strawberry",
    "BlueBerry",
};

var lastFruits = new List<string>();

for (int i = fruits.Length - 1; i >= 0; i--)
{
    lastFruits.Insert(0, fruits[i]);
    if (fruits[i] == "Apple") break;
}

fruits = lastFruits.ToArray();

答案 1 :(得分:1)

查找&#34; Apple&#34;的最后一次出现的索引(根据Euridice01&#39;进行了改进):

var lastAppleIndex = Array.LastIndexOf(fruits, "Apple");

从最后一个&#34; Apple&#34;中提取水果。到最后(感谢Xiaoy312):

var afterAppleFruits = fruits.Skip(lastAppleIndex).ToArray();

适用于大fruits

如果fruits非常大,那么使用ArraySegment会更好:

var afterAppleFruits = new ArraySegment<string>(fruits, lastAppleIndex, fruits.Length-lastAppleIndex);

替代地

我喜欢扩展方法,因此这里有ArraySegment创建方法:

public static ArraySegment<T> Slice<T>(this T[] src, int start, int? count = null) => (count.HasValue ? new ArraySegment<T>(src, start, count.Value) : new ArraySegment<T>(src, start, src.Length-start));

然后你可以说:

var afterAppleFruits = fruits.Slice(lastAppleIndex);

答案 2 :(得分:0)

试试这个;

        string[] fruits = new string[3];
        fruits[0] = "apple";
        fruits[1] = "orange";
        fruits[2] = "banana";

        IList<string> fruitList = fruits.ToList();

        // y index x string value
        foreach (var item in fruitList.Select((x, y) => new { x, y }))
        {
            if (item.x == "apple")
            {
                fruitList.RemoveAt(item.y);
            }
        }

        var result = fruitList;