Home > Blockchain >  How to remove specific Array value like this example?
How to remove specific Array value like this example?

Time:05-22

I want to remove the value "4" in array.

["5" , "4" , "10" , " "]

to

["5" , "10" , " "]

CodePudding user response:

If you know the specific position of the array you can do something like this:

string[] someArray = {"5", "4", "10", ""};
someArray = someArray.Where(w => w != someArray[1]).ToArray();

if you don't you can convert to a list and search for anything and then convert back to array if needed:

string[] someArray = {"5", "4", "10", ""};
List<string> list = new List<string>(someArray);
list.Remove("4");

someArray = list.ToArray();

I saw you asked for function, so here is how you can make some functions I guess too:

void Main()
{
    string[] someArray = {"5", "4", "10", ""};
    var myNewArray = ArrayValueRemove(someArray, "4");
}

// You can define other methods, fields, classes and namespaces here

public string[] ArrayValueRemove(string[] anArray, string valueToRemove)
{
    List<string> list = new List<string>(anArray);
    list.Remove(valueToRemove);

    anArray = list.ToArray();
    
    return anArray;
}

There's no error checking, but you get the point I imagine.

  •  Tags:  
  • c#
  • Related