Methods Calculating a single value
Methods - Calculating a single value
Count() method
The Count() method returns an int
indicating the number of elements in the source sequence that match the predicate
var strings = new List<string> { "first", "then", "and then", "finally" };
// Will return 2
int result = strings.Count(s => s.Contains("e"));
Console.WriteLine(result);
Console.ReadKey();
Sum() method
The result of the Sum() call will be the summation of all of these numerical values of elements in the sequence.
int[] ints = { 2, 2, 4, 6 };
// Will return 14
int result = ints.Sum();
Console.WriteLine(result);
Console.ReadKey();
Min() and Max() methods
Very simply, the Min() method returns the minimum value from the source sequence and the Max() method returns the maximum value. As with the Sum() method, they can only be called on sequences containing numerical values.
int[] ints = { 2, 2, 4, 6, 3, 6, 5 };
// Will return 6
int result = ints.Max();
Console.WriteLine(result);
Any() method
Returns true if at least one of the elements in the source sequence matches the provided predicate. Otherwise it returns false.
var doubles = new List<double> { 1.2, 1.7, 2.5, 2.4 };
// Will return false
bool result = doubles.Any(val => val < 1);
Console.WriteLine(result);
Can you try these for other numerical data types?
Last updated