How to remove Null values in string array
Like { ,-2,3, ,-4,+5, ,66...}
I need to remove those null values in between and re-size the array
I don't want to use lists
I don't want to create a new array
Please let me know if it is possible with simple code.
Thank You.
No, it's not possible without creating a new array. You can't resize an array.
You can easily create a new array without empty strings and null references like this:
string[] items = new string[] { "", "-2", "3", null, "-4", "+5", null, "66" };
items = items.Where(s => !String.IsNullOrEmpty(s)).ToArray();
If you don't want to create a new array, then no, it's not possible. You cannot add or remove an item from a simple array (as in, string[]).
The most straightforward way to accomplish what you want to achieve (if you remove your second requirement) would be:
Count the number of null values in your source array
Create a new array of the same length as your source array minus the number of nulls from step 1
Copy all non-null values from your source array into the new array
(Optional) Set the reference to your source array (e.g., srcArray) to your new array
As Dan said, you can't add or remove values from an Array. You can, however, use LINQ to remove the values and produce a second array.
originalArray = originalArray.Where(s => !string.IsNullOrEmpty(s)).ToArray()
Probably not the most performant solution but...
array.Where(s => s != null).ToArray();
It will create a new array, but I cannot think of a solution that won't.
Before deciding how to proceed, you really need to think about who holds a reference to the array you are operating on.
If the array is not referenced by any other code (as a member of a class, as a captured variable in a lambda, or in some collection somewhere) then you shouldn't worry about creating a new array. In that case I would use something like what #Codesleuth or #Guffa suggest.
However, if other code may exist that holds a reference to this same array - then you are out of luck, unless you can safely identify and update the references held in those other places. This is a hard thing to do - and you should be very careful assuming that you can always update all other places where a reference is held.
Am I the only one here that would scan the array and move the members back over the NULLs, therefore making a continuous list of non-nulls.
This doesn't create a new array and it's simple to implement and it's immportant to know you can move the entries around the array.
Unfortunately I'm at work so can not supply full code, however you would implement it by searching the array for NULLs then moving the remaining items in the array up one. Keep doing this until the end. I would suggest clearing the remaining entires once the search is completed.
string[] _array= new string[] { "", "z", "d", null, "a", "b", null, "66" };
// select non-null elements only
_array= _array.Where(a => !String.IsNullOrEmpty(a)).ToArray();
Related
In C# I'm storing values in an array.
So to create this array I'm using this code, 'int[] values = new int[10];'
But, what if I need more than 10 values, or in the case I never know how many values I will have. Could be 1, 10 or 100.
I understand the idea that I need to let the compiler know how big the array should be so it can allocate memory space for it.
Is there a way to work around that?
You could just use a List and let it do all the heavy lifting for you:
List<int> values = new List<int>();
Arrays must have defined length. If you want dynamic size, consider using List class.
Please take a look at and research the concept of "Immutable objects"
An array has a fixed size, If you need an array with a dynamic size it is best to either create extension methods or a handler that does the work for you.
The work to be done is to get the array, create a new array with the new size based on whether you want to add or remove something, and to populate the new array with the data from the previous array. This will create a new object instead of modifying the previous object and will make sure you don't push items to a full array, or have an array with a size larger than the items that fit in it.
Ofcourse the List class would work as well and would probably solve your problem.
var mylist1 = new List<float>(5);
var mylist2 = new List<float>(new float[5]);
mylist1 gets 5 as a capacity. mylist2 gets 5 too. What is the difference between these two and which one should I use?
The first declaration creates a list with an underlying array with a size of 5.
The second declaration copies data from the passed array to the underlying array in the list.
So the second declaration needs to:
Create an empty array
Copy the values in that array to another array
Since it's also harder to read (what's the point of passing an empty array to a list constructor?), there really isn't any reason at all to use the second instead of the first.
The reason the overload is there is to allow you to prefill the list with values from another array or enumerable. For example:
var list = new List<int>(Enumerable.Range(1, 100));
(though of course, even then you'd usually use Enumerable.Range(1, 100).ToList() instead :))
The first create a List having capacity 5, but empty.i.e, if you access myList1[3] you get an error.
The second create a List of float containing already 5 elements. each element will have value 0.0, i.e the default value for a float
I have a char array in C#.
var arr = new char[3] { 'a','b','c' };
How do I add spaces to the end of it without creating a new array?
result: arr = { 'a', 'b', 'c', ' ', ' ', ' ' };
This might sound similar to VB.NET's ReDim. But I'm not sure that is what I want either.
I want to preserve the elements inside of it and not instantiate a new array behind the scenes.
Is this only possible with Generic Collections and ArrayList?
Thanks
No, this is not possible using an array, generic or otherwise.. AFAIK, there is no way to dynamically resize an array. Use a List instead.
As Martin pointed out in the comments, even the List class uses an array in its internal implementation. If you want to truly be able to dynamically resize a data structure without reinitializing it, you must implement your own version of a linked list.
System.Collections.Generic contains a class called LinkedList that represents a doubly-linked list (meaning that each node has a reference to both the next and the previous node), but I'm not sure if its internal implementation uses an array..
Unfortunately, arrays are pre-fixed by design. This is important because it will reserve the necessary amout of memory at the heap.
So, to answer your requirement about not creating a new one: it won't be possible.
There is, however, a work-around. Look the following method:
Array.Resize(ref myArr, myArr.Length + 5);
It works as described at the source:
This method allocates a new array with the specified size, copies
elements from the old array to the new one, and then replaces the old
array with the new one.
If array is null, this method creates a new array with the specified
size.
If newSize is greater than the Length of the old array, a new array is
allocated and all the elements are copied from the old array to the
new one. If newSize is less than the Length of the old array, a new
array is allocated and elements are copied from the old array to the
new one until the new one is filled; the rest of the elements in the
old array are ignored. If newSize is equal to the Length of the old
array, this method does nothing.
This method is an O(n) operation, where n is newSize.
This means that myArr will be updated to reference the new array. However, if there is another reference to the original array, this won't be updated (it will keep referencing the older version).
Source: MSDN
Let's say that I have 2 string arrays with different values:
string[] sArray1 = new string[3]{"a","b","c"};
string[] sArray2 = new string[3]{"e","f","g"}
And I want to make values of sArray1 equal to values of sArray2 (I know I can write it like this) : sArray1[0] = sArray2[0]; sArray1[1]= sArray2[1]; sArray1[2]=sArray2[2];
For 3 values it's easy, but what if I had 100 values in an array? Is there any other way that I can make array values equal?
p.s. sorry for my bad English :(
Something like this (with a little error checking):
if (sArray2.Length == sArray1.Length)
{
sArray2.CopyTo(sArray1, 0);
}
Regards
I'm assuming you want to keep the reference to the original array in sArray1? Then do this:-
Array.Copy(sArray2, sArray1, sArray1.Length);
If you want them to function independently of each other than you can use .Clone() as of .NET 5.0
string[] sArray1 = (string[])sArray2.Clone();
In the above scenario if you change a value in one array it will not affect the other - this is called a "shallow copy" (AKA copy by val). If you want the values in both arrays to be tied to each other (typically not desirable) you can do a simple assignment like this:
string[] sArray1 = sArray2;
In this case if you change a value in either array the value(s) in the other array will update (AKA copy by ref).
I've just started learning C# and in the introduction to arrays they showed how to establish a variable as an array but is seems that one must specify the length of the array at assignment, so what if I don't know the length of the array?
Arrays must be assigned a length. To allow for any number of elements, use the List class.
For example:
List<int> myInts = new List<int>();
myInts.Add(5);
myInts.Add(10);
myInts.Add(11);
myInts.Count // = 3
Use List<> to build up an 'array' of unknown length.
Use List<>.ToArray() to return a real array, and not a List.
var list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
var array = list.ToArray();
A little background information:
As said, if you want to have a dynamic collection of things, use a List<T>. Internally, a List uses an array for storage too. That array has a fixed size just like any other array. Once an array is declared as having a size, it doesn't change. When you add an item to a List, it's added to the array. Initially, the List starts out with an array that I believe has a length of 16. When you try to add the 17th item to the List, what happens is that a new array is allocated, that's (I think) twice the size of the old one, so 32 items. Then the content of the old array is copied into the new array. So while a List may appear dynamic to the outside observer, internally it has to comply to the rules as well.
And as you might have guessed, the copying and allocation of the arrays isn't free so one should aim to have as few of those as possible and to do that you can specify (in the constructor of List) an initial size of the array, which in a perfect scenario is just big enough to hold everything you want. However, this is micro-optimization and it's unlikely it will ever matter to you, but it's always nice to know what you're actually doing.
You can create an array with the size set to a variable, i.e.
int size = 50;
string[] words = new string[size]; // contains 50 strings
However, that size can't change later on, if you decide you need 100 words. If you need the size to be really dynamic, you'll need to use a different sort of data structure. Try List.
Use an ArrayList if in .NET 1.x, or a List<yourtype> if in .NET 2.0 or 3.x.
Search for them in System.Collections and System.Collections.Generics.
You might also want to look into Dictionarys if your data is unique, This will give you two columns to work with.
User name , Total bill
it gives you a lot of built in tools to search and update just the value.
var yummy = new List<string>();
while(person.FeelsHappy()) {
yummy.Add(person.GetNewFavoriteFood());
}
Console.WriteLine("Sweet! I have a list of size {0}.", list.Count);
Console.WriteLine("I didn't even need to know how big to make it " +
"until I finished making it!");
try a generic list instead of array
In a nutshell, please use Collections and Generics.
It's a must for any C# developer, it's worth spending time to learn :)
As detailed above, the generic List<> is the best way of doing it.
If you're stuck in .NET 1.*, then you will have to use the ArrayList class instead. This does not have compile-time type checking and you also have to add casting - messy.
Successive versions have also implemented various variations - including thread safe variants.
If you really need to use an array instead of a list, then you can create an array whose size is calculated at run time like so...
e.g i want a two dimensional array of size n by n. n will be gotten at run time from the user
int n = 0;
bool isInteger = int.TryParse(Console.ReadLine(), out n);
var x = new int[n,n];