I have a List<String>
with 1000 names. I want to find out the count of names which is starting with letter "S".
What will be the best option to do it?
The easiest way to count the number of occurrences in a Python list of a given item is to use the Python . count() method. The method is applied to a given list and takes a single argument. The argument passed into the method is counted and the number of occurrences of that item in the list is returned.
Use the COUNTIF function to count how many times a particular value appears in a range of cells. For more information, see COUNTIF function.
Operator. countOf() is used for counting the number of occurrences of b in a. It counts the number of occurrences of value. It returns the Count of a number of occurrences of value.
If Linq is available
using System.Linq;
list.Where(s=>s!=null && s.StartsWith("S")).Count();
if Linq is not available.
int count=0;
foreach (string s in list) {
if (s!=null && s.StartsWith("S")) count++;
}
Using linq makes this simple
var count = list.Where(x => x != null && x.StartsWith("S")).Count();
If you have access to LINQ, something like
int count = myList.Count(name => name.StartsWith("S"));
Otherwise, something like
int count = myList.FindAll(name => name.StartsWith("S")).Count;
(Edit: as Bob Vale points out in his answer, if any of your list entries could be null, you need to add a null check e.g. name => name != null && name.StartsWith("S")
.)
int k = 0;
foreach (string aName in yourStringList)
{
if (aName.StartsWith("S"))
{
k++
}
}
and k
will have the number of names which starts with "S"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With