This question already has answers here:
Remove element of a regular array
(15 answers)
Closed 9 years ago.
string[] columns
I want to delete the item on an index specified by a variable of type int.
How do I do this ?
I tried
columns.RemoveAt(MY_INT_HERE);
But apparently this does not works.
Array is immutable class, you can't change it, all you can do is to re-create it:
List<String> list = columns.ToList(); // <- to List which is mutable
list.RemoveAt(MY_INT_HERE); // <- remove
string[] columns = list.ToArray(); // <- back to array
May be the best solution is to redesign your code: change immutable array into List<String>:
List<String> columns = ...
columns.RemoveAt(MY_INT_HERE);
If you don't want to use linq you can use this function :
public string[] RemoveAt(string[] stringArray, int index)
{
if (index < 0 || index >= stringArray.Length)
return stringArray;
var newArray = new string[stringArray.Length - 1];
int j = 0;
for (int i = 0; i < stringArray.Length; i++)
{
if(i == index)continue;
newArray[j] = stringArray[i];
j++;
}
return newArray;
}
You use it like that : columns = RemoveAt(columns, MY_INT_HERE)
You can also make it to an extension method.
You cannot delete items in an array, because the length of a C# array is fixed at the time when it is created, and cannot be changed after that.
You can null out the corresponding element to get rid of the string, or use LINQ to produce a new array, like this:
columns = columns.Take(MY_INT_HERE-1).Concat(columns.Skip(MY_INT_HERE)).ToArray();
You need to add using System.Linq at the top of your C# file in order for this to compile.
However, using a List<string> would be a better solution:
List<string> columns;
columns.RemoveAt(MY_INT_HERE);
Try one of the following (depending on what you need):
columns[MY_INT_HERE] = null;
columns[MY_INT_HERE] = string.Empty;
...otherwise you'll just have to create a new array which has a length of 1 less than your current array, and copy the values over.
If you want something more flexible, you might use a something like a List<string>, where you can use RemoveAt()
Arrays are faster for the computer to work with but slower for a programmer. You will have to find that value with a loop or some other means, then set that position to null. You will end up with an empty space in the array. You could reallocate the array etc etc...
What is easier to use for relatively small amounts of data is a List. You can do myList.RemoveAt(100); and it will work nicely.
You can not delete it.You can recreate the array or I advice you to use List<string> for the same.
List<string> columns = new List<string>();
columns.RemoveAt(1);
It will remove the 2nd element from your List<String> columns
Related
I'm trying to obtain the last 10 objects within an arraylist.
Case: Arraylist full of objects[ChartObjectsInt] and [ChartObjectsReal] with indexes from 0-N, i want to obtain the last 10 persons (N-10), and with these last 10 objects I want to call functions from that object; like ChartObjectsInt.getLabelName();
Can anyone help?
Code I've reached so far:
private void getLastTenObjects()
{
foreach (ChartObjectsInt chartRecords in arraylistMonitor)
{
for (int i = 0; i < 10; i++)
{
arraylistMonitor.IndexOf(i);
}
}
}
Why don't you use List rather than ArrayList, if you do so it will be more easy to get last 10 element from list.
example:
var lastTenProducts = products.OrderByDescending(p => p.ProductDate).Take(10);
//here products is the List
If you don't want to use LINQ at all
for (var i = Math.Max(arraylistMonitor.Count - 10, 0); i < arraylistMonitor.Count; i++)
{
YourFunctionCallHere(arraylistMonitor[i]);
}
The above code will loop through the last 10 items of the ArrayList by setting i to the appropriate starting index - the Math.Max call there is in case the ArrayList has 9 or fewer elements in it.
If you are willing to use LINQ
var last10 = arraylistMonitor.Cast<object>().Reverse().Take(10);
will do what you want. You may also wish to add ToList after Take(10), depending on how you wish to consume last10.
Firstly it casts it to an IEnumerable<object> then goes through the IEnumerable backwards until it has (up to) 10 items.
If you specifically want last10 to be an ArrayList (which I wouldn't recommend) then use:
var last10 = new ArrayList(arraylistMonitor.Cast<object>().Reverse().Take(10).ToList());
As others have already said, I would use List<T> as ArrayList is effectively deprecated for that as it exists from a time when C# didn't have generics.
With that said, you could write a function that would work for a list of any size and take however many like so
public List<T> GetLastX<T>(List<T> list, int amountToTake)
{
return list.Skip(list.Count - amountToTake).ToList();
}
Is this the best way to set each item of a string array to that of an Enumerable array? I came up with this approach on my own, I tried to use my google-foo but couldn't really come up with coherent sentences to describe what i'm trying to do here..
string[] adapterDesc = new string[] {};
int i = 0;
foreach(NetworkInterface adapter in adapters)
{
adapterDesc[i] = adapter.Description;
i++;
}
...
No, that code will fail with an IndexOutOfRange exception because you have declared an array of strings that could contain zero elements.
So when you try to set the first element it will crash.
Instead you could use a List where you can add elements dynamically
List<string> adapterDesc = new List<string>();
foreach(NetworkInterface adapter in adapters)
{
adapterDesc.Add(adapter.Description);
}
...
A List is more flexible than an array because you don't have to know before the size of the array and you could still use it like it was an array
for(int x = 0; x < adapterDesc; x++)
{
Console.WriteLine(adapterDesc[x]);
}
If you want to use Linq then you could even reduce your code to a single line with
string[] adapterDesc = NetworkInterface.GetAllNetworkInterfaces()
.Select(ni => ni.Description)
.ToArray();
This question already has answers here:
How to delete an element from an array in C#
(12 answers)
Closed 7 years ago.
I have an array of email address, but an empty string gets injected into the end of the array. How can I remove this element in the array?
for(int i = 0; i < allToAddresses.Length; i++)
{
if(allToAddresses[i] == " ") // find where empty element is
{ //Here i am trying to delete that empty element. does not work
allToAddresses[i].Split("".ToCharArray(),StringSplitOptions.RemoveEmptyEntries);
}
}
You could try to use Linq for this
allToAddresses = allToAddresses.Where(address=>!string.IsNullOrWhiteSpace(address))
.ToArray();
You have to include also this in your namespaces:
using System.Linq;
You filter your initial array using the Where method. In this method you pass a predicate that returns true if for the current address the method string.IsNullOrWhiteSpace returns false. Otherwise it returns false. Using this filter you discard the addresses that are null, empty, or consisted only of white-space characters.
test = test.Where(x => !string.IsNullOrWhitepace(x)).ToArray();
You cannot truly "remove" elements from an array, because array size is fixed*. You can, however, construct a new array that skips all empty elements:
allToAddresses = allToAddresses.Where(s => !string.IsNullOrWhiteSpace(s)).ToArray();
The above requires using System.Linq at the top of your file. It checks all entries in your array to see if they are null or consist entirely of white space (spaces, tabs, etc.) and produces a new array of strings, containing only non-empty / non-null entries from the original array.
* In the interest of full disclosure, .NET does have an API that lets you modify array size, but you should not use it in situations like this.
If you are using arrays, you will need to pull the valid values out and put them into a new instance of an array. You can do something like this:
internal static T[] RemoveNullArrayElements<T>(T[] array)
{
if (array != null)
{
List<T> newLst = new List<T>();
foreach (var ar in array)
{
if (ar != null)
{
newLst.Add(ar);
}
}
return newLst.ToArray();
}
return array;
}
Could the problem be that you are searching for white space instead of an empty string?
Try below:
for(int i = 0; i < allToAddresses.Length; i++)
{
if(allToAddresses[i] == "") // find where empty element is
{ //Here i am trying to delete that empty element. does not work
allToAddresses[i].Split("".ToCharArray(),StringSplitOptions.RemoveEmptyEntries);
}
}
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
how to inset a new array to my jagged array
i have a problem, where i dont know how i can make a string array variable in array length.
i have this code now below:
string[] p = new string[10];
int num = 0;
foreach (Product products in GetAllProducts())
{
//do something
p[num]= "some variable result"
num++
}
The problem is, that i dont know how many of "p" i will get, although i know it atleast will be less than 10.
but if i put it on 0, i will get an error when i start it, because it doesn't know the "p[num]"
So i am looking for some way to make "p" have a variable length.
anyone could help me out a bit? thanx
============Solved==========
List<string> p = new List<string>();
int num = 0;
foreach (Product products in GetAllProducts())
{
string s= null;
//do something ( create s out of multiple parts += s etc.)
p.add(s)
num++
}
thanx to solution poster
Use an List<string> instead of an array, if you do not know the number of items you will need to add.
Your array length cannot be modified after it has been instantiated. Use ArrayList or Generic Lists.
var p = new new List<string>(10);
foreach (Product products in GetAllProducts())
{
//do something
p.Add("some variable result");
}
What does GetAllProducts() return? Does it have a count or a length?! You should call that first, save it in a variable, get the count/length and then declare your array!
There's two solution.
If you want to keep using array :
int num = 0;
var list = GetAllProducts();
string[] p = new string[list.Length]; // Or list.Count if this is a collection
foreach (Product products in list)
{
//do something
p[num] = "some variable result";
num++;
}
Otherwise you should use a List like this :
List<string> p = new List<string>();
foreach (Product products in GetAllProducts())
{
//do something
p.Add("some variable result");
}
Use Array.Resize() method, which allows to resize it (by n number of indexes).
In my exmaple I will reize by 1 on each step of the way:
string[] array = new string[3]; //create array
for (int i = 0; i < 5; i++)
{
if (array.Length-1 < i) //checking for the available length
{
Array.Resize(ref array, array.Length + 1); //when to small, create a new index
}
array[i] = i.ToString(); //add an item to array[index] - of i
}
Because your code is using a foreach on the result from GetAllProducts, then GetAllProducts must be returning a IEnumerable collection. Probably the best solution would be to simply assign the result of GetAllProducts to such a collection. For example, perhaps it already returns a list of strings? So you can do:
List<string> strings = GetAllProducts();
There is no need to have a foreach loop to create an array when you already have a collection anyway being returned from GetAllProducts.
Or simply:
var strings = GetAllProducts();
to let the compiler work out the type of strings.
Most things you can do with an array you can also do with a List, and some more (such as adding items to the end of the List).
Perhaps you can post the signature of GetAllProducts (especially its return type) so we can better advise you?
I see many gave you the right answer which is the use of Lists. If you still need an array in the end, you can easily convert your list into an Array like this :
string[] tempArray = myList.ToArray();
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Remove element of a regular array
I have a method defined which returns class array.
ex: Sampleclass[]
The Sampleclass has properties Name, Address, City, Zip. On the client side I wanted to loop through the array and remove unwanted items. I am able to loop thru, but not sure how to remove the item.
for (int i = 0; i < Sampleclass.Length; i++)
{
if (Sampleclass[i].Address.Contains(""))
{
**// How to remove ??**
}
}
Arrays are fixed size and don't allow you to remove items once allocated - for this you can use List<T> instead. Alternatively you could use Linq to filter and project to a new array:
var filteredSampleArray = Sampleclass.Where( x => !x.Address.Contains(someString))
.ToArray();
It's not possible to remove from an array in this fashion. Arrays are statically allocated collections who's size doesn't change. You need to use a collection like List<T> instead. With List<T> you could do the following
var i = 0;
while (i < Sampleclass.Count) {
if (Sampleclass[i].Address.Contains("")) {
Sampleclass.RemoveAt(i);
} else {
i++;
}
}