How to count specific element in list with C#

2 Answers

0 votes
using System;
using System.Linq;
using System.Collections.Generic;

class Program
{
    static void Main() {
        var list = new List<int>() { 2, 6, 1, 5, 8, 1, 1, 0, 9, 1 };
        
        int count = list.Count(e => e == 1);

        Console.WriteLine(count); 
    }
}




/*
run:

4

*/

 



answered Sep 4, 2023 by avibootz
0 votes
using System;
using System.Collections.Generic;

class Program
{
    public static int CountElement(List<int> list, int element) {
        int count = 0;
        
        foreach (var e in list) {
            if (e == element) {
                count++;
            }
        }
         
        return count;
    }
    static void Main() {
        var list = new List<int>() { 2, 6, 1, 5, 8, 1, 1, 0, 9, 1 };
        
        int count = CountElement(list, 1);

        Console.WriteLine(count); 
    }
}




/*
run:

4

*/

 



answered Sep 4, 2023 by avibootz

Related questions

1 answer 88 views
1 answer 196 views
1 answer 119 views
2 answers 280 views
2 answers 213 views
...