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.
Related
I basically want to make an array which contains one string[] and one normal string.
onion / {strawberry, banana, grape} in one array.
string[,] foodArray = new string[,] { onion, { strawberry, banana, grape } }
I'm wondering if it's even possible...
Thank you.
This sort of data typing is unclear for what you want to do. Use your types to clearly communicate your intentions
If you plan to lookup by the first string, I might recommend Dictionary<string, List<string>>. The Dictionary collection is an extremely useful collection type
If you want strictly arrays then you must use a jagged array as this will allow you to constrain the first "column" to being only 1 length while the list (2nd column) may be variable length. This would mean string[][] foodArray = new string[1][];
In either case multidimensionals arrays are not suited here, it will lead to wasted space as it allocates all the cells for the dimensions you set. Rule of thumb, always prefer jagged over multidimensional arrays unless you are absolutely sure the entire multidimensional array will be filled to its max in all its dimensions.
I think you do not really want a two dimensional array in this case.
What you really want is an array of a tuple.
using System;
namespace tuple_array
{
using Item = Tuple<String,String[]>;
class Program
{
static void Main(string[] args)
{
Item[] foodarray = new Item[] {
new Item("onion", new string[]
{ "strawberry", "banana", "grape" })
};
foreach (var item in foodarray) {
var (f,fs) = item;
var foo = string.Join(",", fs);
Console.WriteLine($"[{f},[{foo}]]");
}
}
}
}
It looks somewhat clumsy in C#, the F# version is much more terse and pretty:
type A = (string * string []) []
let a : A = [| "onion", [| "strawberry"; "banana"; "grape" |] |]
printfn "%A" a
The question is in title.
What does comma mean as a length of array in C#?
How it is called, how to find it on the Internet?
I searched for "how to initialize array in C#" in google but there is no information about this comma.
If I remove comma VS shows an error: "array initializers can only be used in a variable".
Even after assigning it to variable it still shows error.
EntityFramework generates the following code:
migrationBuilder.InsertData(
table: "Test",
columns: new[] { "Name" },
values: new object[,]
{
{ "Test" },
{ "Test1" }
});
The coma does not represent a length, it represent a dimension. In your case, it can be called a 2d array. It allows you to do this:
values: new object[,]
{
{ "Testa", "Testb", "Testc" },
{ "Test1a", "Test1b", "Test1c" }
}
I'm studying a book with Membership topic in ASP.NET MVC and I found syntax, I cannot trace (and not explained in the book), which is:
new[] {"string"}
like in:
Roles.AddUsersToRoles(new[] {userName}, new[] {roleName});
Per MDSN library I see Roles.AddUsersToRoles method takes two string arrays as arguments, so likely this is a shorthand or would this have some additional functionality?
It is Implicitly Typed Arrays syntax.
You can create an implicitly-typed array in which the type of the
array instance is inferred from the elements specified in the array
initializer.
This
string[] stringArray = new[] {"string"};
is same as :
string[] stringArray = new string[] {"string"};
Other thing to note, the method Roles.AddUsersToRoles accepts two parameters of string type array (and not a string).
public static void AddUsersToRoles(
string[] usernames,
string[] roleNames
)
new string[1] { "string" }
You can omit the array size because the compiler can count the number of elements for you:
new string[ ] { "string" }
You can also omit the array element type because the compiler can infer it from the values provided:
new [ ] { "string" }
But do not get this mixed up with initializers for anonymous types. These do not have the angle brackets [] after new:
new { StringProperty = "string" }
or:
// string StringProperty;
new { StringProperty }
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.
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();
}
}