0

I am trying to get the count of each item in the column that are the same value. for example i have a table that has people info and i want it to go through the first name column and get me a count of how many Joe's and Mary's are in there without specifying a certain name.

LuDevGon
  • 113
  • 1
  • 9

2 Answers2

1

You can group your data by column

users.GroupBy(x => x.FirstName).Select(x => new
{
    FirstName = x.Key,
    Count = x.Count()
});
Alex - Tin Le
  • 1,982
  • 1
  • 6
  • 11
1

Try use GroupBy:

public class People
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    static void Main(string[] args)
    {
        var peoples = new List<People>
        {
            new People { Id = 1, FirstName = "Bob", LastName = "Abc" },
            new People { Id = 2, FirstName = "Joe's", LastName = "Def" },
            new People { Id = 3, FirstName = "Mary's", LastName = "Ghi" },
            new People { Id = 4, FirstName = "Alice", LastName = "Jikl" },
            new People { Id = 5, FirstName = "Bob", LastName = "Mno" },
        };

        var groupedByFirstName = peoples
            .GroupBy(x => x.FirstName)
            .Select(x => new
            {
                FirstName = x.Key,
                Count = x.Count()
            });

        foreach (var people in groupedByFirstName)
        {
            Console.WriteLine($"FirstName: {people.FirstName}. Count: {people.Count}");
        }

        Console.ReadKey();
    }
}