2016-05-08 50 views
1

我正在寻找它,以便计算机测试以查找列表中的元素数量,然后将其保存为变量。如何在c#中将变量中的元素数量保存为变量?

 int incmount = 0; 
     List<int> items = new List<int>(); 
     int numofit = Convert.ToInt32(Console.ReadLine()); 
     for (int i = 0; i < numofit; i++) 
     { 

      items.Add(incmount); 
      incmount++; 

     } 
在上面的例子中

,我想找到元素的列表中的“项目”的数量,并将其保存为一个变量。

+0

你已经有了这个号码。它是_numofit_。你能否解释一下你的意思是什么_列表中的元素数目“items”_ – Steve

+0

该列表被称为项目,在第二行。我想查找该列表中的元素数量。如果稍后再次更改该数字,那么numofit将不再适用于此目的? – LonelyPyxel

+1

好的,但你的代码并不能解释你的问题。不过,我建议你应该搜索这些基本属性的MSDN。例如,你可以在https://msdn.microsoft.com/en-us/library/6sh2ey19(v=vs.110).aspx找到关于泛型列表的所有信息 – Steve

回答

3

元素的列表项目可以通过接入号码:

items.Count 

像这样:

int incmount = 0; 
    List<int> items = new List<int>(); 
    int numofit = Convert.ToInt32(Console.ReadLine()); 
    for (int i = 0; i < numofit; i++) 
    { 

     items.Add(incmount); 
     incmount++; 
    } 
    Console.WriteLine("Number of items: {0}", items.Count); 
1

可以使用

items.Count; 

但如果u需要更有趣

int count = list.Count(i => i > 10);// get the count of those which is bigger than 10