A
A
andoral2017-12-23 21:20:46
C++ / C#
andoral, 2017-12-23 21:20:46

How to count the number of matching objects using LINQ?

There is an array Person[]
Person:

class Person
{
    public string Name {get; set;}
    public DateTime BirthDate {get; set:}
}

You need to filter the array by Name and get an int[] array with the number of births on the same day.
Example: filter - Vasya. Vasya's birthdays - 12/21/90, 05/21/95, 10/23/42
At the exit from person[] should get int[] { 2, 1 }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Arxont, 2017-12-24
@andoral

var persons = new[]
{
    new { Name = "Юрий Васильевич Кондратюк",    BirthDate = new DateTime(1897, 06,  9) },
    new { Name = "Михаил Фёдорович Решетнёв",    BirthDate = new DateTime(1924, 11, 10) },
    new { Name = "Михаил Тимофеевич Калашников", BirthDate = new DateTime(1919, 11, 10) },
    new { Name = "Сергей Павлович Королёв",      BirthDate = new DateTime(1907,  1, 12) },
    new { Name = "Михаил Васильевич Ломоносов",  BirthDate = new DateTime(1711, 11,  8) }
};

int[] arr = persons.Where(n => n.Name.Contains("Михаил"))
                   .GroupBy(day => day.BirthDate.Day)
                   .Select(count => count.Count())
                   .ToArray();        

Array.ForEach(arr, Console.WriteLine);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question