简体   繁体   中英

C# list of array type

I want to create a list of array type. I want to create array containing values :

array = [a,b];

Then i want to put this array in list :

List<Array> list = new List<Array>( );

I am able to do this with list of string type but no luck with array type :

List<String> list = new List<String>( );

I am from javascript background, not much familiar with concept of collections in c#. Also how can i create array in c# like we do in javascript :

var arrTemp = ["a", "b"];

Well, since your array is string[] :

 var arrTemp = ["a", "b"]; 

you have to declare the required list as List<string[]> :

 // list of string arrays
 List<string[]> list = new List<string[]>() {
   new string[] {"a", "b"} 
 };

In case you want to be able to put any array into the list declare it as loose as possible ( List<object[]> ):

 // list of abitrary arrays
 List<object[]> list = new List<object[]>() {
   new string[] {"a", "b"},
   new double[] {123.45, 789.12, 333.55}, 
   new object[] {'a', "bcd", 1, 244.95, true},
 };

希望这可以帮到你

var test = new List<int[]>();

You can actually create a list of arrays:

var listOfArrays = new List<Array>();

The problem with this is that it's difficult to use the arrays themselves, as the Array type doesn't support array syntax. (eg You can't do listOfArrays[0][0] ) Instead, you have to use the GetValue method to do your retrieval:

var obj = listOfArrays[0].GetValue(0);

But this has another problem. The GetValue method returns object , so while you could always cast it to the desired type, you lose your type safety in choosing this approach.

Alternatively, you could just store object[] arrays:

var listOfArrays = new List<object[]>();
var obj = listOfArrays[0][0];

But while this solves the issue of the array notation, you still lose the type safety.

Instead, if at all possible, I would recommend finding a particular type, then just have arrays of that type:

var listOfArrays = new List<string[]>();
string s = listOfArrays[0][0];

for example, an array of strings would be

var arrayOfString = new string[]{"a","b"};
// or shorter form: string[] arrayOfString  = {"a","b"};
// also: var arrayOfString = new[] { "a", "b" }

And then creating a list-of-arrayOfString would be

var listOfArrayOfString = new List<string[]>();

This works with any type, for example if you had a class MyClass

var arrayOfMyClass = new MyClass[]{ ... }; // ... is you creating instances of MyClass
var list = new List<MyClass[]>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM