LINQ | Counting Operator | Count

LINQ has a Count() operator which allows you to count the items which meets the condition in list or array.  You can use using data type’s operators to create a condition for list or array. Let’s take a look at the following example,

using System;
using System.Collections.Generic;
using System.Linq;

namespace ZeroToCSharp {
    class Program {
        static void Main(string[] args) {
            List<int> numberList = new List<int>();
            numberList.Add(8);
            numberList.Add(2);
            numberList.Add(7);

            string[] numberArray = new string[4];
            numberArray[0] = "Zero";
            numberArray[1] = "To";
            numberArray[2] = "CSharp";
            numberArray[3] = "C#";

            int count1 = numberList.Count(x => x > 3);
            int count2 = numberArray.Count(x => x.Length > 4);

            //To print output
            Console.WriteLine(string.Concat("Count of items greater than 3 in list: ", count1));
            Console.WriteLine(string.Concat("Count of items which lengths greater than 4 in array: ", count2));
            Console.ReadKey();
        }
    }
}

 

Output:

Count of items greater than 3 in list: 2
Count of items which lengths greater than 4 in array: 1

 

0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x