BKStart a conversation ↗

LINQ

This is just a quick sample to show you can use LINQ in 2 different yet identical ways.

The task is to show the count of people that have the same ages in our sample input data.

class Program
    {
        class Person
        {
            public string Name { get; set; }
            public int Age { get; set; }
        }
        static void Main(string[] args)
        {
            // some test data
            var info = new List<Person> {
                new Person { Name = "Brian", Age = 34 }, new Person { Name = "Dee", Age = 29 },
                new Person { Name = "Bob", Age = 21 }, new Person { Name = "Dave", Age = 25 },
                new Person { Name = "Tim", Age = 33 }, new Person { Name = "Jacques", Age = 43 },
                new Person { Name = "Simon", Age = 33 }, new Person { Name = "Jame", Age = 34 },
                new Person { Name = "Jason", Age = 34 }, new Person { Name = "Niamh", Age = 34 }};

            var duplicates = from p in info
                             group p by p.Age into g
                             where g.Count() > 1
                             select g;
            Print(duplicates);

            var dups = info.GroupBy(p => p.Age).Where(p => p.Count() > 1);
            Print(duplicates);
        }

        static void Print(IEnumerable<IGrouping<int, Person>> obj)
        {
            obj.ToList().ForEach(p => Console.WriteLine(p.Key + ":" + p.Count()));
        }
    }