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

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

Related

Determine if array contains all zeroes

I create the following array like this:
array<UInt16>^ temp = gcnew array<UInt16>(1000);
How do I determine if this entire array has been filled with zero or not.
I think I may be able to use TrueForAll(T) but I'm not sure.
var allElementsAreZero = temp.All(o => o == 0);
Simple as that.
It'll return when it finds one that doesn't satisfy the condition, so may not necessarily iterate through your whole collection:
"The enumeration of source is stopped as soon as the result can be determined."
https://msdn.microsoft.com/en-us/library/bb548541(v=vs.110).aspx
This should work properly (here I used LINQ):
IEnumerable<int> values = new List<int>(); // Or use any array type instead of List.
... Add your values here ...
var allAreZero = !values.Any(v => v != 0);
P.S. the array class inherits IEnumerable.
And here is a solution with foreach:
var isAllZero = true;
foreach (var value in values)
{
if (value != 0)
{
isAllZero = false;
break;
}
}
UPDATE
The really difference between TrueForAll, and my LINQ code is: LINQ code uses the fluent (or maybe also query) syntax, where TrueForAll is just a normal function where you send the array as a parameter.
initialize a counter from 0 then use for loop to interate through the array and increment the counter whenever it finds 0, and at the end compare the counter with size of array if its equal, it has all zeros
Reading the C++/CLI specification, it has been filled with
0s because you created it with a "new-expression" and the default value of the element type is 0.
24.2 CLI array creation
CLI array instances are created by new-expressions containing gcnew (§15.4.6) or …
Elements of CLI arrays created by new-expressions are always initialized to their default value.

Search for an existing object in a list

This is my first question here so I hope I'm doing right.
I have to create a List of array of integer:
List<int[]> finalList = new List<int[]>();
in order to store all the combinations of K elements with N numbers.
For example:
N=5, K=2 => {1,2},{1,3},{1,4},...
Everything is all right but I want to avoid the repetitions of the same combination in the list({1,2} and {2,1} for example). So before adding the tmpArray (where I temporally store the new combination) in the list, I want to check if it's already stored.
Here it's what I'm doing:
create the tmpArray with the next combination (OK)
sort tmpArray (OK)
check if the List already contains tmpArray with the following code:
if (!finalList.Contains(tmpArray))
finalList.Add(tmpArray);
but it doesn't work. Can anyone help me with this issue?
Array is a reference type - your Contains query will not do what you want (compare all members in order).
You may use something like this:
if (!finalList.Any(x => x.SequenceEqual(tmpArray))
{
finalList.Add(tmpArray);
}
(Make sure you add a using System.Linq to the top of your file)
I suggest you learn more about value vs. reference types, Linq and C# data structure fundamentals. While above query should work it will be slow - O(n*m) where n = number of arrays in finalList and m length of each array.
For larger arrays some precomputing (e.g. a hashcode for each of the arrays) that allows you a faster comparison might be beneficial.
If I remember correctly, contains will either check the value for value data types or it will check the address for object types. An array is an object type, so the contains is only checking if the address in memory is stored in your list. You'll have to check each item in this list and perform some type of algorithm to check that the values of the array are in the list.
Linq, Lambda, or brute force checking comes to mind.
BrokenGlass gives a good suggestion with Linq and Lambda.
Brute Force:
bool itemExists = true;
foreach (int[] ints in finalList)
{
if (ints.Length != tmpArray.Length)
{
itemExists = false;
break;
}
else
{
// Compare each element
for (int i = 0; i < tmpArray.Length; i++)
{
if (ints[i] != tmpArray[i])
{
itemExists = false;
break;
}
}
// Have to check to break from the foreach loop
if (itemExists == false)
{
break;
}
}
}
if (itemExists == false)
{
finalList.add(tmpArray);
}

Check if array cell has a value

I'm grabbing a string of data where each element pair is delimited by the ';' character. So, I do a string split into an array to get each chunk of data.
Each chunk now consists of a label and value pair, which are delimited by a ':'. However, every so often the final element doesn't have a matching value. So for example:
food:cheese
name:dave
car:renault
somethingelse
I'm grabbing these pairs and splitting them into a second array which I then iterate via a foreach like so;
int a=0;
string[,] tmpInfo = new string[10, 2];
foreach(var info in details)
{
string[] tmp = info.Split(':');
if (tmp[1].ToString != null)
{
//do something
}
}
However, when I hit the odd scenario where the last element doesn't have the delimiter, I get an issue with "Index was outside the bounds of the array."
As you can see from my code I tried testing if the array cell was null. I've also tried testing for an empty string, but the issue persists.
Instead of your check if (tmp[1].ToString != null) , check for the Length of returned array like:
if(tmp.Length == 2) //if it should always be 2
In case of empty string or no delimiter in the string you would end up with 1 element in the array. Later when you try to access element at index 1, you will get exception since arrays are 0 based and tmp[1] means access second element of the returned array.

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

C# Remove items from class array [duplicate]

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

Categories

Resources