Arrays must be assigned a length.
C# (.net) Arrays must be assigned a length.
string[] week = new string[7];
week[0] = "Sunday";
week[1] = "Monday";
I've just started learning C# and in the introduction to arrays they showed how to establish a variable as an array but is seems that one must specify the length of the array at assignment, so what if I don't know the length of the array?
Arrays must be assigned a length. To allow for any number of elements, use the List
class.
For example:
List<int> myInts = new List<int>();
myInts.Add(5);
myInts.Add(10);
myInts.Add(11);
myInts.Count // = 3
範例二 :
int[] terms = new int[400];
for (int runs = 0; runs < 400; runs++)
{
terms[runs] = value;
}
List<int> termsList = new List<int>();
for (int runs = 0; runs < 400; runs++)
{
termsList.Add(value);
}
// You can convert it back to an array if you would like to
int[] terms = termsList.ToArray();
去除重覆 {LINQ}
用擴充方法 DISTINCT() 來移除重覆值,最後再利用 ToArary() 轉回 Arrary
int[] arr = new int[] { 1, 2, 2, 3, 3, 3, 4, 4, 4, 4 };
int[] result = arr.Distinct().ToArray();
資料來源:
https://stackoverflow.com/questions/599369/array-of-an-unknown-length-in-c-sharp
https://stackoverflow.com/questions/202813/adding-values-to-a-c-sharp-array