Counting elements in arrays and List

String array elements can be counted like this;

string[] empty = new string[5];
var totalCount = empty.Count(); //5

string[] flower = {"Red Rose", "White Rose", "Yellow Rose", "Clover", "Cameilla"};

totalCount = flower.Count(); //5
var cloverCount = flower.Count(x => x == "Clover");

List elements can be counted like this;

var flower = new List<string>() {"Red Rose", "White Rose", "Yellow Rose", "Clover", "Cameilla" };
var count = flower.Count();
var listCount = flower.Count(x => x.Contains("Clover"));

and if you have a custom class, do this;

flower.count(x => x.flowerName == "Clover");

FavoriteLoadingAdd to favorites
Spread the love

Author: Shahzad Khan

Software developer / Architect