2013-03-20 66 views
0

我有一个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中,然后使用索引来计算列表的数量。

+0

为什么你不能做bigList.Count? – cDima 2013-03-20 18:35:51

+0

bigList.Count是我所有列表的数量,它是20个正确的,这不是我所要求的。我需要内部列表的数量。 – stackdaddy 2013-03-20 18:38:07

+0

'List'只是一个'ArrayList',它不需要强制转换,具有一些额外的方法,并且不包含值。然而,你可以使用'ArrayList'来解决它,你可以使用你的列表,它只需要更少的投射。 – Servy 2013-03-20 18:38:30

回答

4

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

var s = bigList[i].Count; 

进去每个内部列表中的全部项目,这样做:

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

我不知道为什么我这样挣扎时,它是如此明显..... – stackdaddy 2013-03-20 18:40:08

+0

没问题,只要记住upvote答案,帮助你,并接受回答你的问题最好的时候,你可以:) – 2013-03-20 18:41:35

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()); 
+0

你可能不希望在这种情况下使用'Count()'LINQ扩展方法,因为它通过列举枚举'O(n)'时间 - 使用List的'Count'属性来代替列表的长度时间不变。 – 2013-03-20 18:39:49

+1

@CallumRogers实际上,LINQ的Count()方法有一个优化;如果提供的序列可以转换为“ICollection”,则它会这样做并使用它的“Count”属性,因此在这种情况下它实际上是O(1)。 – Servy 2013-03-20 18:45:00

+0

@Servy:刚刚反编译它,它似乎你是对的:http://pastebin.com/hj8r0YjT!然而,这种优化是依赖于实现的 - 我不知道单个或可移植.NET是否会这样做,其中Count属性在所有这些属性上都是O(1)。 – 2013-03-20 18:50:12

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

如何:

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

如何像:

bigList.Sum(smallList => smallList.Count()); 
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 
} 

列表/ ArrayList中都实现了IList接口,所以你可以以相同的方式使用它们。