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.
CodePudding user response:
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 arrays will be filled to its max
CodePudding user response:
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
CodePudding user response:
Check for Tuple
var foodTuple = new Tuple<string, string[]>("onion", new string[] { "strawberry", "banana", "grape" });