简体   繁体   English

C#中的List数组

[英]An array of List in c#

I want to have an array of Lists.我想要一个列表数组。 In c++ I do like:在 C++ 中,我喜欢:

List<int> a[100];

which is an array of 100 Lists.这是一个包含 100 个列表的数组。 each list can contain many elements.每个列表可以包含许多元素。 I don't know how to do this in c#.我不知道如何在 C# 中做到这一点。 Can anyone help me?谁能帮我?

You do like this:你喜欢这样:

List<int>[] a = new List<int>[100];

Now you have an array of type List<int> containing 100 null references.现在您有一个List<int>类型的数组,其中包含 100 个空引用。 You have to create lists and put in the array, for example:您必须创建列表并放入数组,例如:

a[0] = new List<int>();

Since no context was given to this question and you are a relatively new user, I want to make sure that you are aware that you can have a list of lists.由于没有给出这个问题的上下文,而且你是一个相对较新的用户,我想确保你知道你可以有一个列表列表。 It's not the same as array of list and you asked specifically for that, but nevertheless:它与列表数组不同,您是专门为此询问的,但是:

List<List<int>> myList = new List<List<int>>();

you can initialize them through collection initializers like so:您可以通过集合初始化程序来初始化它们,如下所示:

List<List<int>> myList = new List<List<int>>(){{1,2,3},{4,5,6},{7,8,9}};

simple approach:简单的方法:

        List<int>[] a = new List<int>[100];
        for (int i = 0; i < a.Length; i++)
        {
            a[i] = new List<int>();
        }

or LINQ approachLINQ方法

        var b = Enumerable.Range(0,100).Select((i)=>new List<int>()).ToArray();

我可以建议您使用 linq 在同一行创建和初始化数组:

List<int>[] a = new List<int>[100].Select(item=>new List<int>()).ToArray();
List<int>[]  a = new List<int>[100];

You still would have to allocate each individual list in the array before you can use it though:您仍然需要在数组中分配每个单独的列表,然后才能使用它:

for (int i = 0; i < a.Length; i++)
    a[i] = new List<int>();

采用

List<int>[] a = new List<int>[100];
// The letter "t" is usually letter "i"//

    for(t=0;t<x[t];t++)
    {

         printf(" %2d          || %7d \n ",t,x[t]);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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