C# Remove items from class array [duplicate] - c#

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++;
}
}

Related

C# RemoveAt from list one item at a time [duplicate]

This question already has answers here:
Collection was modified; enumeration operation may not execute
(16 answers)
Closed 4 years ago.
I am trying to remove one item from the list until the list is empty. My code only successfully removes one item from the list and then cause an error. How do I fix this?
public void ReleaseAllAnimals()
{
int i = 0;
foreach (var value in _farmAnimals)
{
_farmAnimals.RemoveAt(i);
Console.WriteLine(value.Species());
i++;
}
}
You should not be modifying the collection while enumerating it. As you want to remove elements you should use for loop instead with indexer so that you do not face the issue.
You can loop through the list in reverse order like and remove from the end item one by one:
for(int i=_farmAnimals.Count -1; i >= 0; i--)
{
var species = _farmAnimals[i].Species(); // get species of current item
_farmAnimals.RemoveAt(i); // remove from list
Console.WriteLine(species); // display it
}
You can remove each item from the first of your List by using RemoveAt(0)
Change your code to this:
int size = _farmAnimals.Count;
for(int i = 0; i < size; i++)
{
var s = _farmAnimals[0].Species();
Console.WriteLine(s);
_farmAnimals.RemoveAt(0);
}
I hope it helps you

Get the last 10 objects in arraylist

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();
}

How do I remove an empty element in an array? [duplicate]

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);
}
}

Initialize List<> with some count of elements [duplicate]

This question already has answers here:
How to initialize a List<T> to a given size (as opposed to capacity)?
(16 answers)
Initialize a List<int> with LINQ query
(6 answers)
Closed 8 years ago.
let's say I have a simple List<bool>. I want to initialize it and add e.g 100 elements to it. To do so, I can do:
var myList = new List<bool>();
for (int i = 0; i < 100; i++)
{
myList.Add(false);
}
but it's not the most elegant approach. Is there any built-in method to simplify it ? I don't want any loops, just for curiosity
Using Enumerable.Repeat
var myList = Enumerable.Repeat(false, 100).ToList();
which
Generates a sequence that contains one repeated value.
false is easy, since it's the default value of boolean:
new List<bool>(new bool[100]);
You could use LINQ and more specifically the Select and ToList extension methods:
var myList = Enumerable.Range(1, 100).Select(x => false).ToList();
List<T> has no specific method to do this. The loop is your best option.
However, you can make it more efficient at runtime, by initializing the list with an initial capacity:
var myList = new List<bool>(100);
When using this constructor, the list will internally allocate an array of 100 elements. If you use the default constructor, it will start of with first 0 and then 4 elements. After 4 items have been added, the list will allocate an array of 8 elements and copy the 4 that were already added over. Then it will grow to 16, 32, 64 and finally 128. All these allocations and copy operations can be avoided by using the constructor with the initial capacity.
Alternatively, if you need to do this in different places in your program, you could make an extension method:
public static void Initialize<T>(this List<T> list, T value, int count)
{
if (list == null)
{
throw new ArgumentNullException("list");
}
if (list.Count != 0)
{
throw new InvalidOperationException("list already initialized");
}
if (list.Capacity < count)
{
list.Capacity = count;
}
for (int i = 0, i < count, i++)
{
list.Add(value);
}
}
You would use it like this:
var myList = new List<bool>();
myList.Initialize(false, 100);
The other option that you have is to use an array.
var myList = new bool[100];
The interesting thing about this specific example is that you do not have to initialize the array. Since false is the default value for bool, all elements in the array will automatically have the value false. If your list does not need to resize dynamically, this is certainly an option to consider.
You can use List.AddRange:
List<bool> list = new List<bool>();
list.AddRange(Enumerable.Repeat(default(bool), 100));

Deleting a specific item of an array [duplicate]

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

Categories

Resources