如何获得内部列表计数?

时间:2013-03-20 18:34:20

标签: c# list

我有一个List,' bigList'它包含List我的自定义类。因此,如果我的' bigList'中有20个列表,我如何获得其中一个内部列表的计数?

List<List<myClass>> bigList = new List<List<myClass>>();
for (int i = 0; i < 20; i++)
{
     List<myClass> newList = new List<myClass>();

     for (int i = 0; i < 100; i++)
     {
          newList.Add(myClass);
     }
     bigList.Add(newList);
}

通过此示例,如何获取bigList中列表的计数?我没有和List一起工作ArrayList我做错了,因为我只是将列表存储在ArrayList中然后使用索引来计算列表的数量

6 个答案:

答案 0 :(得分:5)

要获取i列表的Count属性,请执行以下操作:

var s = bigList[i].Count;

要获取每个内部列表中的总项目,请执行以下操作:

bigList.Sum(x => x.Count);

答案 1 :(得分:2)

// To get the number of Lists which bigList holds
bigList.Count();

// To get the number of items in each List of bigList
bigList.Select(x => new {List = x, Count = x.Count()});

// To get the count of all items in all Lists of bigList
bigList.Sum(x => x.Count());

答案 2 :(得分:1)

foreach (List<myClass> innerList in bigList)
{
     int count = innerList.Count;
}

答案 3 :(得分:1)

怎么样:

foreach(var innerList in bigList)
    var size = innerList.Count; //use the size variable

答案 4 :(得分:1)

如下:

bigList.Sum(smallList => smallList.Count ());

答案 5 :(得分:1)

bigList[0].Count; //accesses the first element of the big list and retrieves the number of elements of that list item

或者,在大列表中每个元素的foreach循环中:

for (var item in bigList)
{
   Console.WriteLine(item.Count); // print number of elements for every sublist in bigList
}

List / ArrayList都实现了IList接口,因此您可以以相同的方式使用它们。

相关问题