Q:
How to access
Q:
How to use the
Q:
How does the c
Laparoscopic diagn
The present invent
Bahrain’s Foreign
Newport Beach, Cal
A group of interna
Methotrexate-assoc
Q:
PHP Regex - NoQ:
How to convert a list into int in c#
I have a list of integers and I want to count the length of that list but the value of the list is List.
In my code it displays like this:
How can i convert it into an int?
This is my code:
foreach (var item in list_number)
{
numbers = numbers + 1;
}
A:
Use the .Count() extension method, which will give you the Count of the list:
var count = list_number.Count();
A:
I believe you mean the Count() method. The foreach loop you have will assign each element to a variable named item, but then it will perform the addition, which is not what you want.
foreach (var item in list_number)
{
numbers = numbers + 1;
}
would be better as:
numbers = list_number.Count();
This will give you the number of elements in the list.
EDIT: It looks like you want the size of the list (which is more than just its count), so you can do:
int size = list_number.Count;
This will get the size of the list into the size variable.
A:
var size = list_number.Count;
Or you could use the List.Count Property
A:
You can just use a variable for the Count and add 1 to it:
int sum = 0;
foreach (var item in list_number)
{
sum++;
}
Or, better yet, use a LINQ Extension method:
int sum = list_number.Count();
The Count method will loop through the List and only count the items in it.
The Count property is a convenient way of getting the count without having to loop through the items and add one to a variable. It will do all the incrementing for you.
When you're working with lists, there are several different ways of getting the count. Check them out here:
How to get the size of a list?
The Count property is just syntactic sugar for calling the IList Count property, but you're still adding one to the total.