# NMath User's Guide

38.3 Counts and Sums (.NET, C#, CSharp, VB, Visual Basic, F#)

The static Count() method on class StatsFunctions returns the number of elements in a data set:

Code Example – C#

```int numElements = StatsFunctions.Count( data );
```

Code Example – VB

```Dim NumElements As Integer = StatsFunctions.Count(Data)
```

Counts() returns an IDictionary of key-value pairs in which the keys are the unique elements in a given data set, and the values are the counts for each element.

CountIf() calculates how many elements in a data set return true when a logical function is applied. For example, suppose MeetsThreshold() is a method that returns true if a given numeric value is greater than 100:

Code Example – C#

```public bool MeetsThreshold( double x )
```
```{
```
```  return ( x > 100 );
```
```}
```

Code Example – VB

```Public Function MeetsThreshold(X As Double) As Boolean
```
```  Return (X > 100)
```
```End Function
```

This code counts the number of elements in a data set that meet the criterion:

Code Example – C#

```int num = StatsFunctions.CountIf( data, new
```
```  new Func<double, bool>( MeetsThreshold ) );
```

Code Example – VB

```Dim Num As Integer = StatsFunctions.CountIf(DataArray,
```
```  New Func(Of Double, Boolean)(AddressOf MeetsThreshold))
```

Similarly, the static Sum() method sums the elements in a data set. SumIf() sums the elements in a data set that return true when a logical function is applied:

Code Example – C#

```double sum = StatsFunctions.SumIf( data, new
```
```  new Func<double, bool>( MeetsThreshold ) );
```

Code Example – VB

```Dim Sum As Double = StatsFunctions.SumIf(DataColumn,
```
```  New Func(Of Double, Boolean)(AddressOf MeetsThreshold))
```

An overload of SumIf() sums the elements in one data set based on evaluating a logical function on another data set. For instance, this code sums the elements in data2 that correspond to those elements in data where MeetsThreshold() returns true:

Code Example – C#

```double sum = StatsFunctions.SumIf( data, function, data2 );
```

Code Example – VB

```Dim Sum As Double = StatsFunctions.SumIf(DataVector, MyFunction,
```
```  data2)
```

A MismatchedSizeException is raised if the two data sets do not have the same number of elements.

Top

Top