I has a multidimentional string array as below
string[][] data = new string[3][];
the item in the string array as below
data[0]
[0] "EUG5" string
[1] "FA1" string
data[1]
[0] "9.000000" string
[1] "1000" string
data[2]
[0] "1" string
[1] "0" string
I wish to remove the data[0][1], data[1][1] and data[2][1], this is base on the condition on data[2] where it is "0". Is it possible to do this?
You can use Array.Resize to do what you want to do. Try this LINQpad script:
var data = new string[][]{new []{"EUG5","FA1"},new []{"9.000000","1000"},new []{"1","0"}};
data.Dump();
Array.Resize(ref data[0],1);
Array.Resize(ref data[1],1);
Array.Resize(ref data[2],1);
data.Dump();
It produces this:
You can also use Array.Copy to move elements around, so this is the more generic case:
var data = new string[][]{new []{"EUG5","FA1"},new []{"9.000000","1000"},new []{"1","0"}};
data.Dump();
var colToDelete = 0;
for (int i = 0; i < data.Length; i++)
{
Array.Copy(data[i],colToDelete+1,data[i],colToDelete,data[i].Length-colToDelete-1);
Array.Resize(ref data[i],data[i].Length-1);
}
data.Dump();
but like the other posters correctly state, it's way easier with a List.
You cannot remove elements from an Array object in C#, all Arrays are immutable. To get the flexibility you are looking for you want to use the List object.
If for some reason you are stuck and have to use arrays, then you could make a method that accepts an Array and Returns an Array. Then you could remove the objects like this:
public string[][] RemoveElement(string[][] array, int coordinateA, int coordinateB)
{
var ListOfItems = new List<List<string>>();
foreach(string[] item in array)
ListOfItems.add(new List<string>(item));
ListOfItems[coordinateA].RemoveAt(coordinateB);
var ReturnArray = new string[ListOfItems.Length][]();
for(int i = 0; i < ListOfItems.Length; i++)
ReturnArray[i] = ListOfItems[i].ToArray();
return ReturnArray;
}
Of couse this is not a very optimized solution, but it will get the job done. There probably are extension method solutions for removing elements from arrays, but it would be far better to just use List object, and then return an array at the end of your code by calling List.ToArray() if it is necessary.
If you don't mind in creating new Array of Arrays instead of reusing existing array you could do this.
data = data
.Select(x=> data[2][1] == "0"? // Condition to filter
x.Take(1).ToArray()
: x.ToArray())
.ToArray();
Check this Demo
Related
I have an array :
string[] arr = new string[2]
arr[0] = "a=01"
arr[1] = "b=02"
How can I take those number out and make a new array to store them? What I am expecting is :
int [] newArr = new int[2]
Inside newArr, there are 2 elements, one is '01' and the other one is '02' which both from arr.
Another way besides Substring to get the desired result is to use String.Split on the = character. This is assuming the string will always have the format of letters and numbers, separated by a =, with no other = characters in the input string.
for (var i = 0; i < arr.Length; i++)
{
// Split the array item on the `=` character.
// This results in an array of two items ("a" and "01" for the first item)
var tmp = arr[i].Split('=');
// If there are fewer than 2 items in the array, there was not a =
// character to split on, so continue to the next item.
if (tmp.Length < 2)
{
continue;
}
// Try to parse the second item in the tmp array (which is the number
// in the provided example input) as an Int32.
int num;
if (Int32.TryParse(tmp[1], out num))
{
// If the parse is succesful, assign the int to the corresponding
// index of the new array.
newArr[i] = num;
}
}
This can be shortened in a lambda expression like the other answer like so:
var newArr = arr.Select(x => Int32.Parse(x.Split('=')[1])).ToArray();
Though doing it with Int32.Parse can result in an exception if the provided string is not an integer. This also assumes that there is a = character, with only numbers to the right of it.
Take a substring and then parse as int.
var newArr = arr.Select(x=>Int32.Parse(x.Substring(2))).ToArray();
As other answers have noted, it's quite compact to use linq. PM100 wrote:
var newArr = arr.Select(x=>Int32.Parse(x.Substring(2))).ToArray();
You asked what x was.. that linq statement there is conceptually the equivalent of something like:
List<int> nums = new List<int>();
foreach(string x in arr)
nums.Add(Int32.Parse(x.Substring(2);
var newArr = nums.ToArray();
It's not exactly the same, internally linq probably doesn't use a List, but it embodies the same concept - for each element (called x) in the string array, cut the start off it, parse the result as an int, add it to a collection, convert the collection to an array
Sometimes I think linq is overused; here probably efficiencies could be gained by directly declaring an int array the size of the string one and filling it directly, rather than adding to a List or other collection, that is later turned into an int array. Proponents of either style could easily be found; linq is compact and makes relatively trivial work of more long hand constructs such as loops within loops within loops. Though not necessarily easy to work out for those unfamiliar with how to read it it does bring a certain self documenting aspect to code because it uses English words like Any, Where, Distinct and these more quickly convey a concept than does looking at a loop code that exits early when a test returns true (Any) or builds a dictionary/hashset from all elements and returns it (Distinct)
I have trouble with the value that arraylist returns.
I created a two-dimensional Arraylist that includes string arrays, when I try to get actual value of string arrays, I get System.String[] as output
instead of actual value of the arrays.
Why do I get System.String() as outuput?
Here is my code :
static void Main(string[] args)
{
string[] employee_1 = { "Employee1" };
string[] employee_2 = { "Employee2" };
ArrayList main_array = new ArrayList();
main_array.Add(employee_1);
main_array.Add(employee_2);
for (int i= 0; i < 2; i++)
{
Console.WriteLine(main_array[i]);
}
Console.ReadKey();
}
That is because when retrieving the items from an ArrayList what you are getting is a reference to an object instead of the actual type. Thus when printing it is calls the ToString of object (which prints the type's name) and not the string you want. In addition when printing a collection (like you are doing in your WriteLine command) you need to specify how to so do because it's default implementation is also as object's. You can use string.Join to print all items in the nested array.
To correct this first cast to string[] ( as string[]) and then print, or better still is to work with the list object instead: List<string[]>. To read more see:
ArrayList vs List<> in C#
What is the difference between an Array, ArrayList and a List?
So:
var mainCollection = new List<string[]> { new string[] { "Employee1" },
new string[] { "Employee2" }};
for (int i = 0; i < mainCollection.Count; i++)
{
Console.WriteLine(string.Join(", ", mainCollection[i]));
}
Console.ReadKey();
As a side note do not loop to 2 but instead by the number of items in the collection. See: What is a magic number, and why is it bad?
This is the default behaviour of ToString() function for an array.
To print the employees names, you need to iterate the array:
for (int i= 0; i < 2; i++)
{
foreach(string employee in main_array[i]) {
Console.WriteLine(employee);
}
}
The problem is here, ArrayList always take input as an object. So, when you add string array at an ArrayList, it take an object instead of string array.
So, you should convert this object to string array and print it.
like below:
for (int i = 0; i < 2; i++)
{
Console.WriteLine(string.Join(", ", main_array[i] as string[]));
}
or may use below(both are same):
for (int i = 0; i < 2; i++)
{
foreach (string employee in main_array[i] as string[])
{
Console.WriteLine(employee);
}
}
Because you have string[] type elements in outer ArrayList.
The best examples to enumerate are in answers above. If you realy need string content of string to be wtitten you should use
Console.WriteLine(((string[])main_array[i])[0]);
main_array is a two position ArrayList, each position contains a string[] this is, a string array.
If you use main_array[0], this is a reference to employee_1 which is a string array.
You should be able to reference the array strings by using main_array[0][0]
Try this:
foreach(var strArray in main_array)
{
// strArray is a string array
foreach(var stir in strArray)
{
// star is a string
Console.WriteLine(str);
}
}
Given a read only collection of ints, how do I convert it to a byte array?
ReadOnlyCollection<int> collection = new List<int> { 118,48,46,56,46,50 }.AsReadOnly(); //v0.8.2
What will an elegant way to convert 'collection' to byte[] ?
You can use LINQ's Select method to cast each element from int to byte.
This will give you an IEnumerable<byte>. You can then use the ToArray() extension method to convert this to a byte[].
collection.Select(i => (byte)i).ToArray();
If you don't want to use LINQ then you can instantiate the array and use a for loop to iterate over the collection instead, assigning each value in the array.
var byteArray = new byte[collection.Count];
for (var i = 0; i < collection.Count; i++)
{
byteArray[i] = (byte)collection[i];
}
How to remove item from a simple array once? For example, a char array contains these letters:
a,b,d,a
I would like to remove the letter "a" one time, then the result would be:
a,b,d
Removing an item from an array is not really possible. The size of an array is immutable once allocated. There is no way to remove an element per say. You can overwrite / clear an element but the size of the array won't change.
If you want to actually remove an element and change the size of the collection then you should use List<char> instead of char[]. Then you can use the RemoveAt API
List<char> list = ...;
list.RemoveAt(3);
If your goal is to just skip the first 'a', then remove the second, you could use something like:
int first = Array.IndexOf(theArray, 'a');
if (first != -1)
{
int second = Array.IndexOf(theArray, 'a', first+1);
if (second != -1)
{
theArray = theArray.Take(second - 1).Concat(theArray.Skip(second+1)).ToArray();
}
}
If you just need to remove any of the 'a' characters (since you specified that the order is not relevant), you could use:
int index = Array.IndexOf(theArray, 'a');
if (index != -1)
{
theArray = theArray.Take(index - 1).Concat(theArray.Skip(index+1)).ToArray();
}
Note that these don't actually remove the item from the array - they create a new array with that element missing from the newly created array. Since arrays are not designed to change in total length once created, this is typically the best alternative.
If you will be doing this frequently, you may want to use a collection type that does allow simple removal of elements. Switching from an array to a List<char>, for example, makes removal far simpler, as List<T> supports simple APIs such as use List<T>.Remove directly.
You can use linq by trying the following
var someArray= new string[3];
someArray[0] = "a";
someArray[1] = "b";
someArray[2] = "c";
someArray= someArray.Where(sa => !sa.Equals("a")).ToArray();
Please note: This method is not removing the element from the array but that it is creating a new array that is excluding the element. This may have an effect on performance.
You might consider using a list or collection.
static void Main(string[] args)
{
char[] arr = "aababde".ToArray();
arr = RemoveCharacter(arr, 'a');
arr = RemoveCharacter(arr, 'b');
arr = RemoveCharacter(arr, 'd');
arr = RemoveCharacter(arr, 'z');
arr = RemoveCharacter(arr, 'a');
//result is 'a' 'b' 'e'
}
static char[] RemoveCharacter(char[] array, char c)
{
List<char> list = array.ToList();
list.Remove(c);
return list.ToArray();
}
I have an array:
String[] ay = {
"blah",
"blah number 2"
"etc" };
... But now I want to add to this array at a later time, but I see no option to do so. How can this be done? I keep getting a message saying that the String cannot be converted to String[].
Thank you
Use a List rather than an array:
List<string> list = new List<string>();
list.Add( "blah" ) ;
Then, later, if you really do need it as an array:
string[] ay = list.ToArray();
Arrays are of fixed size, so after it has been created, you can't change the size of it (without creating a new array object)
Use the List<string> instead of the array.
Arrays can't change their size after they are declared. Use collections instead. For example: List.
As everyone's already said, use List in the System.Collections.Generic namespace.
You could also use a Hashtable which will allow you to give each string a meaning, or "key" which gives you an easy way to pull out a certain string with a keyword. (as for keeping messages stored in memory space for whatever purpose.)
You could also Create a new array each time you add a value, make the new array 1 bigger than the old one, copy all the data from the first array into the 2nd array, and then add your new value in the last slot (Length - 1)
Then replace the old array with your new one.
It's the most manual way of doing it.
But List and Hashtable work perfectly well too.
If you don't need indexing a specific array element (usage of brackets), but you want to be able to efficiently add or remove elements, you could use LinkedList.
If you do need indexing
have a look at Dictionary data type also in the System.Collection
http://msdn.microsoft.com/en-us/library/xfhwa508.aspx
so you could do something like
Dictionary<int, string> dictionary = new Dictionary<int, string>();
dictionary.Add(1, "afljsd");
You can do this but I don't recommend it:
// Reallocates an array with a new size, and copies the contents
// of the old array to the new array.
// Arguments:
// oldArray the old array, to be reallocated.
// newSize the new array size.
// Returns A new array with the same contents.
public static System.Array ResizeArray (System.Array oldArray, int newSize) {
int oldSize = oldArray.Length;
System.Type elementType = oldArray.GetType().GetElementType();
System.Array newArray = System.Array.CreateInstance(elementType,newSize);
int preserveLength = System.Math.Min(oldSize,newSize);
if (preserveLength > 0)
System.Array.Copy (oldArray,newArray,preserveLength);
return newArray;
}
Here's an extension method to add the to arrays together and create a new string array
public static class StringArrayExtension
{
public static string[] GetStringArray (this string[] currentArray, string[] arrayToAdd)
{
List<String> list = new List<String>(currentArray);
list.AddRange(arrayToAdd);
return list.ToArray();
}
}