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

   1:  class Program
   2:      {
   3:          class Person
   4:          {
   5:              public string Name { get; set; }
   6:              public int Age { get; set; }
   7:          }
   8:          static void Main(string[] args)
   9:          {
  10:              // some test data
  11:              var info = new List<Person> {
  12:                  new Person { Name = "Brian", Age = 34 }, new Person { Name = "Dee", Age = 29 },                
  13:                  new Person { Name = "Bob", Age = 21 }, new Person { Name = "Dave", Age = 25 },
  14:                  new Person { Name = "Tim", Age = 33 }, new Person { Name = "Jacques", Age = 43 },
  15:                  new Person { Name = "Simon", Age = 33 }, new Person { Name = "Jame", Age = 34 },
  16:                  new Person { Name = "Jason", Age = 34 }, new Person { Name = "Niamh", Age = 34 }};
  17:              
  18:              var duplicates = from p in info
  19:                               group p by p.Age into g
  20:                               where g.Count() > 1
  21:                               select g;
  22:              Print(duplicates);            
  23:   
  24:              var dups = info.GroupBy(p => p.Age).Where(p => p.Count() > 1);
  25:              Print(duplicates);
  26:          }
  27:   
  28:          static void Print(IEnumerable<IGrouping<int, Person>> obj)
  29:          {
  30:              obj.ToList().ForEach(p => Console.WriteLine(p.Key + ":" + p.Count()));
  31:          }
  32:      }

 

image

Comments are closed