I try to convert this simple array to an array of arrays of arrays
string[] test = new string[] { "a", "b", "c" };
I am looking for the fellow output once serialised by JSON.NET.
[[["a"]],[["b"]],[["c"]]]
Any ideas ?
To get an array of array of arrays, you'd use the Select method, and use it to project each string into an array of arrays, with the original string in the inner array.
var arrayOfArrayOfArrays = test.Select(s => new[] { new[] { s } }).ToArray();
And of course don't forget to call ToArray at the end, otherwise you'll end up with an IEnumerable of array of arrays.
Related
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
var movieNext = new string[,]
{
{ "superhero", "action", "waltdisney", "bat"},
{"superhero", "action", "marvel",""},
{"history", "action", "malay", "" },
{"malay", "novel", "", ""},
{"history", "bat", "", ""}
};
The above code is a multidimensional array, which stores a sequence of movie's keyword. Is there a way to implement this without having to put the blank strings in the array initialization?
For example you can see in the above code, I have to put the blank string "" to fill up the array.
You could use a jagged array instead.
string[][] movieNext = new string[][] { { etc... } }.
You can consider C# jagged array (though they are different from multi-dimensional arrays).
string[][] movieNext = {
new [] { "superhero", "action", "waltdisney", "bat"},
new [] {"superhero", "action", "marvel"}, <and so on>
};
If you want to stick with multi-dimensional arrays, you have to initialize the values individually. If you don't provide any string value for any of the index (i,j) by default it will be null.
I suggest never to use two-dimensional arrays. They have practically no support in the API (you'll be hard pressed to find a method that accepts a two-dimensional array as a parameter), and cannot be cast to IEnumerable<T> or similar well-supported interface. As such, you can really use them only in the most local of scopes.
Instead, I suggest you use something castable to IEnumerable<IEnumerable<string>>. Oh, another tip. Check this out. Specifically,
To initialize a Dictionary, or any collection whose Add method takes multiple parameters, enclose each set of parameters in braces as shown in the following example.
Thus, the following will work:
class Program
{
static void Main(string[] args)
{
var d = new ManyList()
{
{"Hi", "Good", "People", "None", "Other"}
{"Maybe", "Someone", "Else", "Whatever"}
};
Console.Read();
}
}
class ManyList : List<string>
{
public void Add(params string[] strs)
{
Console.WriteLine(string.Join(", ", strs));
}
}
This might help you clean up your syntax a bit.
I am attempting to iterate over a 2d string array but my foreach statement has a compile error that I dont understand.
What am I doing wrong in this simple example & how can I perform what I am trying to do?
string URL = PRODUCT_URL + "?";
string[,] a = {{"a","1"},{"b","2"}};
foreach (string[] param in a) // error cannot convert type string to string[]
{
URL += param[0] + "=" + param[1] + "&";
}
C# has two similar constructs, Arrays of arrays and multidimensional arrays. What you have here is a 2 dimensional array, so the loop you want is
foreach (string param in a)
{
...
}
If you wanted to go the array of arrays approach, you'd want:
string[][] a = {new[] {"a","1"}, new[] {"b","2"}}
for your declaration.
Internally, C# implements the multidimensional array as a normal array with a size equal to the product of the dimension (e.g. since your a is 2x2, it would be a linear array of length 4). This way, the programmer can use a more convenient syntax for member access and initialization.
A 2-dimensional array of string is not the same as an array of arrays of string.
A 2-D Array string[,] is not the same as string[][] (like C/C++), despite the initialization.
http://msdn.microsoft.com/en-us/library/2yd9wwz4.aspx
You have to write the code like this:
string URL = PRODUCT_URL + "?";
string[][] a = { new[] { "a", "1" }, new[] { "b", "2" } };
foreach (string[] param in a) // error cannot convert type string to string[]
{
URL += param[0] + "=" + param[1] + "&";
}
With your code you are iterating a,1,b,2 (4 loops).
If not what's the best way to create it ?
Note: merging is not just appending, it fusionned keys that are the same.
This functionality exist on a List element. Arrays are fixed width items in C#, so you can't modify the size without creating a new array. However, Lists are a different story. You can do:
List<int> sample = oldList.AddRange(someOtherList);
// sample contains oldList with all elements of someOtherList appended to it.
Additionally, with LINQ it's trivially easy to convert between List and Array with the
.ToList()
.ToArray()
extension methods. If you want to do that with an indeterminate number of arrays, you could do something like this:
public static class ArrayExtensions
{
public static T[] MergeArrays<T>(this T[] sourceArray, params T[][] additionalArrays)
{
List<int> elements = sourceArray.ToList();
if(additionalArrays != null)
{
foreach(var array in additionalArrays)
elements.AddRange(array.ToList());
}
return elements.ToArray();
}
}
And call:
int[] mergedArray = initialArray.MergeArrays(array1, array2, array3 /* etc */);
You can use the LINQ Concat() method:
using System.Linq;
// ...
var arr1 = new[] { 1, 2, 3 };
var arr2 = new[] { 4, 5, 6 };
var merged = arr1.Concat(arr2); // This returns an IEnumerable<int>
// If you want an actual array, you can use:
var mergedArray = merged.ToArray();
Duplicate. Already discussed here:
Most efficient way to append arrays in C#?
You can't merge arrays as arrays have fixed size in C#. There are numerous ways to do this with enumerables and List.
No not directly equivalent to array_merge.
If you just want to merge two arrays there is already another question : Merging two arrays in .NET
If your looking for a direct array merge replacement there is none.
How is an array of string where you do not know where the array size in c#.NET?
String[] array = new String[]; // this does not work
Is there a specific reason why you need to use an array? If you don't know the size before hand you might want to use List<String>
List<String> list = new List<String>();
list.Add("Hello");
list.Add("world");
list.Add("!");
Console.WriteLine(list[2]);
Will give you an output of
!
MSDN - List(T) for more information
You don't have to specify the size of an array when you instantiate it.
You can still declare the array and instantiate it later. For instance:
string[] myArray;
...
myArray = new string[size];
You can't create an array without a size. You'd need to use a list for that.
you can declare an empty array like below
String[] arr = new String[]{}; // declare an empty array
String[] arr2 = {"A", "B"}; // declare and assign values to an array
arr = arr2; // assign valued array to empty array
you can't assign values to above empty array like below
arr[0] = "A"; // you can't do this
As others have mentioned you can use a List<String> (which I agree would be a better choice). In the event that you need the String[] (to pass to an existing method that requires it for instance) you can always retrieve an array from the list (which is a copy of the List<T>'s inner array) like this:
String[] s = yourListOfString.ToArray();
I think you may be looking for the StringBuilder class. If not, then the generic List class in string form:
List<string> myStringList = new List<string();
myStringList.Add("Test 1");
myStringList.Add("Test 2");
Or, if you need to be absolutely sure that the strings remain in order:
Queue<string> myStringInOriginalOrder = new Queue<string();
myStringInOriginalOrder.Enqueue("Testing...");
myStringInOriginalOrder.Enqueue("1...");
myStringInOriginalOrder.Enqueue("2...");
myStringInOriginalOrder.Enqueue("3...");
Remember, with the List class, the order of the items is an implementation detail and you are not guaranteed that they will stay in the same order you put them in.
I suppose that the array size if a computed value.
int size = ComputeArraySize();
// Then
String[] array = new String[size];
Can you use a List strings and then when you are done use strings.ToArray() to get the array of strings to work with?
If you will later know the length of the array you can create the initial array like this:
String[] array;
And later when you know the length you can finish initializing it like this
array = new String[42];
If you want to use array without knowing the size first you have to declare it and later you can instantiate it like
string[] myArray;
...
...
myArray=new string[someItems.count];
string[ ] array = {};
// it is not null instead it is empty.
string foo = "Apple, Plum, Cherry";
string[] myArr = null;
myArr = foo.Split(',');