Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding count of particular items from a list

Tags:

c#

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?

like image 455
Vishnu Avatar asked Oct 16 '12 09:10

Vishnu


People also ask

How do I count a specific item in a list in Python?

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.

How do you count how many times a value appears in a list?

Use the COUNTIF function to count how many times a particular value appears in a range of cells. For more information, see COUNTIF function.

How do you find the number of occurrences of a string in a list?

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.


4 Answers

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++;
}
like image 159
Bob Vale Avatar answered Oct 09 '22 11:10

Bob Vale


Using linq makes this simple

var count = list.Where(x => x != null && x.StartsWith("S")).Count();
like image 38
Ash Burlaczenko Avatar answered Oct 09 '22 13:10

Ash Burlaczenko


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").)

like image 24
Rawling Avatar answered Oct 09 '22 11:10

Rawling


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"

like image 41
Dejo Avatar answered Oct 09 '22 13:10

Dejo